2

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!

Omar
  • 16,329
  • 10
  • 48
  • 66
NJohns
  • 53
  • 2
  • 2
  • 7
  • Have you tried a javascript solution or do you need to postback? If the DDLs are always going to equal eachother, why do you need both? – MikeSmithDev Nov 12 '12 at 20:45

2 Answers2

6

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;
}
codingbiz
  • 26,179
  • 8
  • 59
  • 96
1

Seems like the NamingContainer is not a row, so leave it like that. It already has the FindControl method.

var row = ddlLabTest.NamingContainer;
Amiram Korach
  • 13,056
  • 3
  • 28
  • 30