c# dropdownlist selectedindexchanged in gridview sets selectedindex of second dropdownlist

NJohns picture NJohns · Nov 12, 2012 · Viewed 17.8k times · Source

I have a gridview with two dropdownlists populated from a db. One is a descriptive name, the other is an abbreviated name. I need to accomplish the following:

When I select an item in DDL1 I need to change the selected index of DDL2 to match, and vice versa.

I have searched on here and found the following:

protected void ddlAddLabTest_SelectedIndexChanged(object sender, EventArgs e)
{
   DropDownList ddlLabTest = (DropDownList)sender;
   GridViewRow row = (GridViewRow)ddlLabTest.NamingContainer;
   DropDownList ddlAddLabTestShortName = (DropDownList)row.FindControl("ddlAddShortname");

   ddlAddLabTestShortName.SelectedIndex = intSelectedIndex;
}

Only when it gets to the assignment for "row" I receive the following:

Unable to cast object of type 'System.Web.UI.WebControls.DataGridItem' to type 'System.Web.UI.WebControls.GridViewRow'.

I have tried finding a working example but I can't. Any help is greatly appreciated!

Answer

codingbiz picture codingbiz · Nov 12, 2012

Try this

protected void ddlAddLabTest_SelectedIndexChanged(object sender, EventArgs e)
{
   DropDownList ddlLabTest = (DropDownList)sender;
   DataGridItem row = (DataGridItem) ddlLabTest.NamingContainer;
   DropDownList ddlAddLabTestShortName = (DropDownList)row.FindControl("ddlAddShortname");

   ddlAddLabTestShortName.SelectedIndex = intSelectedIndex;
}