How to insert DropdownList control in a GridView Control

This sample is to demonstrate how you can insert a DropdownList ASP.Net control into a GridView control. Since DropdownList is not one of the standard bound controls in GridView, you will make use of ItemTemplate column to insert your DropdownList control. This way your combobox will show in each row of the view. But you only want to bind DropdownList control to data that is relevant to the row in which it is being rendered. That means you will have to get data for your DropdownList in each row. You can accomplish in multiple ways. One of the ways will be to get relationship key between the row data that data for DropdownList and then execute a SELECT statement to get data for DropdownList.

In the example for this article, I created a GridView to show PostTitle, DateCreated and Categories for blog posts. For demo purposes I want to show categories of each post in a dropdown combo box. So the mark up for GridView looks as below.


<Columns>
	<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
	<asp:BoundField DataField="DateCreated" HeaderText="DateCreated" 
		SortExpression="DateCreated" />
	<asp:TemplateField>
		<ItemTemplate>
		  <asp:DropDownList ID="ddlCategories" 
        runat="server" DataTextField="CategoryName">
       </asp:DropDownList>
		</ItemTemplate>
	</asp:TemplateField>
</Columns>

I defined two SqlDataSource objects to specify my SELECT queries. The query for data for DropdownList is parameterized and needs to take PostID in WHERE clause. You can subscribe for onrowdatabound event of GridView. This event is fired when each DataRow gets data bound before rendering. You can access DataItem for the row and extract values that you need to execue query for data for DropdownList. Following code snippet shows how you can accomplish binding of DropdownList to source in this event.


protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
  DropDownList ddl = e.Row.FindControl("ddlCategories") as DropDownList;
  if (null != ddl)
  {
   // Get PostID from data item.
   DataRowView drv = e.Row.DataItem as DataRowView;
   SqlDataSource2.SelectParameters["PostID"].DefaultValue = drv["PostID"].ToString();
   ddl.DataSource = 
    SqlDataSource2.Select(DataSourceSelectArguments.Empty);
   ddl.DataBind();
  }
 }
}

Search

Social

Weather

1.5 °C / 34.8 °F

weather conditions Clouds

Monthly Posts

Blog Tags