Skip to content

ASP: Change Event of a Control inside an ItemTemplate of a GridView and the Respective DataKey

The change events of a control like the DropDownList that is placed inside an ItemTemplate of a GridView does not give you the DataKey of the specific GridRow were the change has happened.

In order to get the DataKey you have to use the controls NamingContainer:

protected void CommType_SelectedIndexChanged(object sender, EventArgs e)
{
	DropDownList d = sender as DropDownList;
	int companyID = 0;

	if (d != null)
	{
		GridViewRow r = d.NamingContainer as GridViewRow;

		if (r != null)
			companyID = Convert.ToInt32(grvCompanies.DataKeys[r.DataItemIndex].Value);
	}
}

This is the event handler for a DropDownList called CommType. The GridViewRow is the parent container which allows access to the DataKey using the row’s DataItemIndex.

 

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

*