Home
Manage Your Code
Snippet: DropDownList inside a GridView (or DataGrid) (C#)
Title: DropDownList inside a GridView (or DataGrid) Language: C#
Description: DropDownList inside a GridView (or DataGrid) Views: 539
Author: msdn yahoo Date Added: 1/16/2008
Copy Code  
1<asp:GridView ID="gvStates" AutoGenerateColumns="false" runat="server" OnRowCreated="gvStates_RowCreated">
2<Columns>
3  <asp:BoundField HeaderText="State" DataField="Name" />
4  <asp:TemplateField HeaderText="Cities">
5    <ItemTemplate>
6      <asp:DropDownList ID="ddlCities" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddlCities_SelectedIndexChanged">
7      </asp:DropDownList>
8    </ItemTemplate>
9  </asp:TemplateField>
10</Columns>
11</asp:GridView>
12<asp:Label ID="lblCity" runat="server" Text="Label"></asp:Label>
13
14
15protected void Page_Load(object sender, EventArgs e)
16    {
17      if (!IsPostBack)
18      {
19        // Create states array and bind it to Grid
20        ArrayList states = new ArrayList();
21        string[] cities = new string[] { "Portland", "Salem", "Eugene" };
22        State state = new State("OR", cities);
23        states.Add(state);
24        cities = new string[] { "Seattle", "Tacoma", "Olympia" };
25        state = new State("WA", cities);
26        states.Add(state);
27        this.gvStates.DataSource = states;
28        this.gvStates.DataBind();
29      }
30    }
31  protected void gvStates_RowCreated(object sender, GridViewRowEventArgs e)
32  {
33    if (!IsPostBack)
34    {
35      if (e.Row.RowType == DataControlRowType.DataRow)
36      {
37        // Bind drop down to cities
38        DropDownList ddl = (DropDownList)e.Row.FindControl("ddlCities");
39        ddl.DataSource = ((State)e.Row.DataItem).Cities;
40        ddl.DataBind();
41      }
42    }
43  }
44  protected void ddlCities_SelectedIndexChanged(object sender, EventArgs e) 
45  {
46    this.lblCity.Text = ((DropDownList)sender).SelectedValue; 
47  }
Usage
The page requirements:
1) Table/Grid displays a list of states (U.S. states) with a column for the state name and a column that contains a dropdown list of the state's cities.
2) Upon selecting a city, the page will display the city name (and perhaps futher lookup some information specific to the city).

The basic ASP.NET flow here is (using 2.0 here, but works similarly in 1.1 using DataGrid):
1) Create a GridView with a bound column for state and a template column for the DropDownList
2) Create a label to display the city name upon selecting it in the DropDownList.
3) Bind the GridView to an array of state objects (could be bound to many other things as well, but keeping it simple for this example). State contains properties for Name and for Cities.
4) Hookup RowCreated event on the GridView so that we can populate the cities into the particular row's DropDownList.
5) Add postback event for getting the selected city and populating the label with it.