Click here to Skip to main content
15,892,072 members
Articles / Web Development / ASP.NET

DataGrid with dropdown column

Rate me:
Please Sign up or sign in to vote.
1.26/5 (12 votes)
17 Oct 2005CPOL1 min read 96.9K   26   7
This article shows how to create and populate a DropDownList column inside a DataGrid.

DropDown list inside a DataGrid

Introduction

We come across requirements of having custom controls to be kept in DataGrid columns, such as textbox columns, image columns, hyperlink columns, or dropdown columns. In the case of most of such columns, pointing to the appropriate data source and showing data is easy. However, in the case of columns containing dropdown lists where the data needs to be retrieved and shown in each row by making a database call, it becomes a little tricky. In such scenarios, we get stuck many a time, and don't have a solution. This article addresses this issue, and shows a sample code snippet demonstrating how to achieve this. This article can address other commonly faced issues like:

  • Inserting a new row in the DataGrid with a dropdown list shown populated.
  • Having each row's dropdown list populated with a different data source.

It would be a good idea to address these issues in detail in separate articles rather than clubbing everything here.

Using the code

The sample code below shows:

  • How to create a DataGrid with a column containing a DropDownList control in HTML (ASPX page).
  • How to populate the DropDownList control contained within the DataGrid column by doing data binding for the DropDownList in the "ItemDatabound()" event handler of the DataGrid.
HTML (ASPX page) showing how to create the DataGrid with a DropDownList control.
ASP.NET
//
//    The HTML code for defining a datagrid with a custom column say containing a 
//    DropDown list is shown below. The ID given to the DropDown list control here 
//    uniquely identifies it and should be given a meaningful name. This ID will
//    be used in code behind file while populating it.
//

<asp:datagrid id="ProductsGrid" runat="server" 
        Width="280px" ShowFooter="True" 
        AutoGenerateColumns="False" ShowHeader="False">
    <Columns>
        <asp:TemplateColumn>
            <ItemTemplate>
                <asp:dropdownlist CssClass="CellValue" 
                    Width="255px" BackColor="#ffffff" 
                    id="ProductsDescription" Runat="server">
                </asp:dropdownlist>
            </ItemTemplate>
            <FooterTemplate>
                <asp:dropdownlist CssClass="CellValue" 
                    Width="255px" id="NewProductsDescription" 
                    BackColor="#ffcc66" runat="server">
                </asp:dropdownlist>
            </FooterTemplate>
        </asp:TemplateColumn>
    </Columns>
</asp:datagrid>
Code-behind (.aspx.cs file) showing how to populate the DropDownList control by making a database call.
C#
private void ProductsGrid_ItemDataBound(object sender, 
        System.Web.UI.WebControls.DataGridItemEventArgs e)
{
    //    Get the data from DB to populate the DropDownlist
    SqlConnection conn = new 
      SqlConnection(ConfigurationSettings.AppSettings.Get("ConnectionString"));
                
    DataSet result = new DataSet();


    string cmdText = "Select * from tbl_Products ORDER BY Description";
    SqlDataAdapter dataAdapter = new SqlDataAdapter(cmdText, conn);

    try
    {
        dataAdapter.Fill(result, "Products");

        if(e.Item.ItemType == ListItemType.AlternatingItem ||
            e.Item.ItemType == ListItemType.Item)    
        {
            //    Find the drop down control from datagrid items
            DropDownList list = (DropDownList)
               e.Item.FindControl("ProductsDescription");

            //    Set the text and value properties
            // for the dropdown list to appropriate columns in the
            //     data source
            list.DataTextField = "Description";
            list.DataValueField = "ID";
            list.DataSource = result.Tables["Products"];
            list.DataBind();

            //     Get the footer row and set
            // the properties for the dropdown column there also
            if(e.Item.ItemType == ListItemType.Footer)
            {
                DropDownList list = (DropDownList)
                  e.Item.FindControl("NewMicrosoftProductsDescription"); 
                list.DataTextField = "Description";
                list.DataValueField = "ID";
                list.DataSource = result.Tables["MSProducts"];
                list.DataBind();
                int count = list.Items.Count;
            }
        }
    }
    catch (Exception ex)
    {
        Response.Write("<script language="JavaScript">" + 
            " alert('Populating products list failed with exception: \\'" + 
            ex.Message.Replace("'", "\\'") + 
            "\\'. Close the window and contact" + 
            " Admin!!'); window.close();</script>");

        return;
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralScript/compile Pin
SpiritMinded29-Oct-09 10:45
SpiritMinded29-Oct-09 10:45 
QuestionHow about retriving the selected item on edit mode Pin
firestoper17-Jul-07 20:50
firestoper17-Jul-07 20:50 
AnswerRe: How about retriving the selected item on edit mode Pin
Hovik Melkomian7-May-08 22:25
Hovik Melkomian7-May-08 22:25 
QuestionWhat triggers the "ProductsGrid_ItemDataBound"? Pin
Web Troubadour12-Mar-07 11:09
Web Troubadour12-Mar-07 11:09 
GeneralThanks for the tip Pin
nsimeonov17-Jan-06 8:43
nsimeonov17-Jan-06 8:43 
GeneralRe: Thanks for the tip Pin
Sudrani17-Jan-06 8:49
Sudrani17-Jan-06 8:49 
GeneralRe: Thanks for the tip Pin
nsimeonov17-Jan-06 8:53
nsimeonov17-Jan-06 8:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.