Thursday, September 3, 2009

Adding and Binding A DropDownList Control In Footer of GridView Control

In this post I will show you how you can add DropDownList control in the grid view footer and also binding DropDownList control to the data source. Let us start with the example code. First you have to add the footer to the grid view control by setting the ShowFooter property to true. Next you have to add the dropDownList control to the footer of the any of the column in the grid view. Here I have added country DropDownList in the footer of the country column in the grid view control, this DropDownList control will contain the names of the countries in the grid view, by selecting the distinct country name from the current pages records. Here is the html code to add the DropDownList control in the footer of the country column in the grid view control.
<HeaderTemplate >
<asp:Label ID="lblheader" runat="server" Text='Country'></asp:Label>
<asp:Label ID="txtLabel" runat="server" Text='<%# Bind("Country") %>'></asp:Label>
<asp:DropDownList ID="ddlDropDownList" runat ="server" ></asp:DropDownList>
And here is the code for the RowDataBound event of the grid view control, here I have first check for the row type , as I am looking for the footer row of the grid view control, So I check for the row type of footer, if current row is footer row then I will search for the ddlDropDownList control which is the dropDownList control added in the footer of the country column in the grid view control. After the FindControl I have check to see if the DropDownList Control is found or not if true, then I have set the DataSource and the DataTextField of the DropDownList control and then at the end I have call the DataBind of the DropwDownList control.

if (e.Row.RowType == DataControlRowType.Footer)
DropDownList ddlDropDownList = (DropDownList)e.Row.FindControl("ddlDropDownList");
if (ddlDropDownList != null)
ddlDropDownList.DataSource = dtsCustomer.Tables[1];
ddlDropDownList.DataTextField = "Country";
Here is the output of the above work, You can see the DropDownList in the footer of the Country column of the grid view control.

You can download the source code from here

Note: In the Source code you can find script of a store procedure which you need to execute in the northwind database, And remember you have to replace the alter keyword with the Create so new store procedure will be created.
All and any comments / bugs / suggestions are welcomed!


Anonymous said...

If the gridview is not having any data initially but just has an empty data template with dropdownlist how to bind these dropdownlists?

Prince said...

its really gud artical..and help me alot..thanx bro. and keep it up.
Prince Kumar