C# How to access a dropdownbox in a listview?

Go To StackoverFlow.com


I have a listview. In my listview I have a dropdownbox which I want to fill in my codebehind page. Only the thing is, I don't know how to access this webcontrol. The following doesn't work:

DropDownList ddl = (DropDownList)lvUserOverview.Controls[0];

I know the index is 0 because the dropdownlist is the only control on the listview (also when I try index 1 I get a index out of range exception).

Can someone tell me how i can access the dropdownlist? In my pagebehind I want to add listitems.

ASPX Code :

<asp:DropDownList ID="ddlRole" onload="ddlRole_Load" runat="server">


protected void ddlRole_Load(object sender, EventArgs e)
  DropDownList ddl = (DropDownList)lvUserOverview.FindControl("ddlRole");
  if (ddl != null)
      foreach (Role role in roles)
          ddl.Items.Add(new ListItem(role.Description, role.Id.ToString()));
2009-06-16 13:40
by Martijn
Can you show your complete code of ASPX page... or you can send me in email.. I think there is something in ASPX page which is creating issue? - Muhammad Akhtar 2009-06-22 07:52


To get a handle to the drop down list inside of its own Load event handler, all you need to do is cast sender as a DropDownList.

DropDownList ddlRole = sender as DropDownList;
2009-06-16 16:27
by Bryan Batchelder
Thnx. Is it possible to send an extra parameter? Maybe so that eventArgs gets an extra property? something like this: and in the codebehind in the load event: e.id Hope you get what I mean - Martijn 2009-06-18 07:15


If this is being rendered in a ListView then there's a chance that multiple DropDownLists are going to be instantiated, each will get a unique ID and you wouldn't be able to use Matthew's approach.

You might want to use the ItemDataBound event to access e.Item.FindControl("NameOfDropDownList") which will allow you to iterate on each dropdown created.

If you are only creating one... why it is in a ListView?

2009-06-16 13:49
by Lazarus
See my startpos - Martijn 2009-06-16 14:18


Try this:

DropDownList ddl = (DropDownList)lvUserOverview.FindControl("NameOfDropDownList");
2009-06-16 13:42
by Matthew Jones
The ID of my dropdownlist is set to ddlRole. When I use DropDownList ddl = (DropDownList)lvUserOverview.FindControl("ddlRole"); it doesn't work - Martijn 2009-06-16 13:47
Post your ASPX code for the ListView, maybe there is a problem with it - Matthew Jones 2009-06-16 13:49
See my startpos - Martijn 2009-06-16 14:14


If your controls are data bound, make sure you try to access their descendents after data binding. I may also help just inspecting objects in debugger before that line.

2009-06-16 13:50
by Dmitry Tashkinov