Dynamically Create and Add DropDownList to a GridView Control in Asp.Net C# and VB

← PrevNext →

You can use Asp.Net GridView control’s built-in functions to add or bind a DropDownList to each cell. I have shared a simple example on this before. Please read this post here. However, you can also programmatically create and add DropDownList to the GridView based on certain conditions. In-addition, I’ll show you how to add event to the dynamically created DropDownList to get the selected values.

Programmaticically create and add DropDownList to a GridView control using CSharp in Asp.Net

The advantage of creating and adding a DropDownList dynamically using code behind procedure, is that you can create the control according to your requirement, using a condition and control its behavior.

The Markup

I have added a GridView control on my web page and set few properties. Important to note, that I have set the AutoGenerateColumns property as true.

Recommended: How to Add Items Dynamically to a DropDownList with the Click of a Button in Asp.Net C#

<asp:GridView ID="GridView" 
    AutoGenerateColumns="true"
    GridLines="None" 
    runat="server">
</asp:GridView>
Code Behind (C#)
using System;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class SiteMaster : System.Web.UI.MasterPage
{
    System.Data.DataTable mytable = new System.Data.DataTable();

    protected void Page_Load(object sender, EventArgs e)
    {
        CreateGrid();
        AddRowsToGrid();

        // NOW BIND THE GRIDVIEW WITH THE DATATABLE. 
        GridView.DataSource = mytable;
        GridView.DataBind();
    }

    private void CreateGrid()
    {
        System.Data.DataColumn tColumn = null;      // TABLE COLUMNS.

        tColumn = new System.Data.DataColumn("Product", System.Type.GetType("System.String"));
        mytable.Columns.Add(tColumn);
        tColumn = new System.Data.DataColumn("Stock", System.Type.GetType("System.String"));
        mytable.Columns.Add(tColumn);
        tColumn = new System.Data.DataColumn("Quantity", System.Type.GetType("System.String"));
        mytable.Columns.Add(tColumn);
        tColumn = new System.Data.DataColumn(" ", System.Type.GetType("System.String"));
        mytable.Columns.Add(tColumn);
    }

    private void AddRowsToGrid()
    {
        // ADD ROWS TO THE DATATABLE.
        mytable.Rows.Add("Samsung", "Available", "15");
        mytable.Rows.Add("Micromax", "Out of Stock", "0");
        mytable.Rows.Add("iPhone", "Available", "9");
        mytable.Rows.Add("Oppo", "Available", "21");
        mytable.Rows.Add("Sony", "Out of Stock", "0");
    }

    protected void GridView_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if ((e.Row.Cells[1].Text).ToUpper() == "OUT OF STOCK")
            {
                // CHANGE THE COLOR OF THE CELL.
                e.Row.Cells[1].BackColor = System.Drawing.Color.Crimson;
                e.Row.Cells[1].ForeColor = System.Drawing.Color.WhiteSmoke;

                // CREATE A LINK BUTTON.
                LinkButton lb = new LinkButton();
                lb.ID = e.Row.Cells[0].Text;
                lb.Text = "Update";
                // ADD LINK BUTTON CLICKED EVENT.
                lb.Click += new EventHandler(LinkClicked);

                // NOW CREATE A DROPDOWN LIST CONTROL.
                DropDownList ddl = new DropDownList();
                ddl.ID = "ddl " + e.Row.Cells[0].Text;
                ddl.SelectedIndex = 0;
                ddl.Items.Add("10");
                ddl.Items.Add("20");
                ddl.Items.Add("30");
                // ADD DROPDOWN CHANGED EVENT.
                ddl.SelectedIndexChanged += new EventHandler(DropDown_Changed);

                // BIND LINK BUTTON AND DROPDOWN LIST TO THE GRID.
                e.Row.Cells[3].Controls.Add(lb);
                e.Row.Cells[3].Controls.Add(ddl);
            }
        }
    }
    
    // GET DROPDOWNLIST SELECTED VALUE.
    protected void DropDown_Changed(object sender, EventArgs e)
    {
        DropDownList ddl = (DropDownList)sender;
        ViewState["QTY"] = ddl.Text;
    }

    protected void LinkClicked(object sender, EventArgs e)
    {
        LinkButton lnk = (LinkButton)sender;
        if (!string.IsNullOrEmpty((lnk.ID)))
        {
            // UPDATE QANITITY FOR THE SELECTED PRODUCT.
            string sUpdate = "";
            sUpdate = "UPDATE dbo.Stock SET Quantity = " + ViewState["QTY"] + " WHERE Product = '" + lnk.ID + "'";

            // CODE TO UPDATE DATABASE ...
        }
    }
}

Don’t get overwhelmed by the length of the code. The main function (to focus) in the above code is GridView_RowDataBound, where I am creating and adding DropDownList to the grid dynamically.

I am creating and populating the GridView with some fixed values. I am also using the DataTable class and its properties to create the grid, add columns and finally add rows to the grid.

While adding the rows to the GridView, it raises the RowDataBound event, that’s where I am checking if the first cell (column name Stock) is out-of-stock. If true, I’ll create a DropDownList and add it to the last cell of the grid. The last cell (column) is blank.

Also Read: Programmatically or Dynamically add LinkButton to a GridView in Asp.Net – C# and Vb

If you have noticed, I am creating a LinkButton too. This is optional. Both the controls are bound to an event. LinkButton has a click event [lb.Click += new EventHandler(LinkClicked);] and DropDownList has DropDown_Changed event [ddl.SelectedIndexChanged += new EventHandler(DropDown_Changed);]. It will raise event when you change the value in the DropDownList and click the LinkButton.

Note: Please check the Vb code (below) if you are a Visual Basic programmer.

Now I need to get the selected value from the DropDownList, so I can update my database. The selected value extraction code is inside the DropDown_Changed event.

protected void DropDown_Changed(object sender, EventArgs e)
{
    DropDownList ddl = (DropDownList)sender;
    ViewState["QTY"] = ddl.Text;
}
Code Behind (Vb)

I have explained the code in the above section (after C# code).

Option Explicit On
Partial Class Site
    Inherits System.Web.UI.MasterPage

    Dim mytable As New Data.DataTable()
    Dim dr As Data.DataRow

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        CreateGrid()
        AddRowsToGrid()

        ' NOW BIND THE GRIDVIEW WITH THE DATATABLE.
        GridView.DataSource = mytable
        GridView.DataBind()
    End Sub

    Private Sub CreateGrid()
        Dim tColumn As Data.DataColumn          ' TABLE COLUMNS.

        tColumn = New Data.DataColumn("Product", System.Type.GetType("System.String"))
        mytable.Columns.Add(tColumn)
        tColumn = New Data.DataColumn("Stock", System.Type.GetType("System.String"))
        mytable.Columns.Add(tColumn)
        tColumn = New Data.DataColumn("Quantity", System.Type.GetType("System.String"))
        mytable.Columns.Add(tColumn)
        tColumn = New Data.DataColumn(" ", System.Type.GetType("System.String"))
        mytable.Columns.Add(tColumn)
    End Sub

    Private Sub AddRowsToGrid()
        ' ADD ROWS TO THE DATATABLE.

        mytable.Rows.Add("Samsung", "Available", "15")
        mytable.Rows.Add("Micromax", "Out of Stock", "0")
        mytable.Rows.Add("iPhone", "Available", "9")
        mytable.Rows.Add("Oppo", "Available", "21")
        mytable.Rows.Add("Sony", "Out of Stock", "0")
    End Sub

    Protected Sub GridView_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            If UCase(e.Row.Cells(1).Text) = "OUT OF STOCK" Then

                ' CHANGE THE COLOR OF THE CELL.
                e.Row.Cells(1).BackColor = Drawing.Color.Crimson
                e.Row.Cells(1).ForeColor = Drawing.Color.WhiteSmoke

                ' CREATE A LINK BUTTON.
                Dim lb = New LinkButton()
                lb.ID = e.Row.Cells(0).Text
                lb.Text = "Update"
                AddHandler lb.Click, AddressOf LinkClicked      ' ADD LINK BUTTON CLICKED EVENT.

                ' NOW CREATE A DROPDOWN LIST CONTROL.
                Dim ddl = New DropDownList()
                ddl.ID = "ddl " & e.Row.Cells(0).Text
                ddl.SelectedIndex = 0
                ddl.Items.Add("10")
                ddl.Items.Add("20")
                ddl.Items.Add("30")
                ' ADD DROPDOWN CHANGED EVENT.
                AddHandler ddl.SelectedIndexChanged, AddressOf DropDown_Changed

                ' BIND LINK BUTTON AND DROPDOWN LIST TO THE GRID.
                e.Row.Cells(3).Controls.Add(lb)
                e.Row.Cells(3).Controls.Add(ddl)
            End If
        End If
    End Sub

    ' GET DROPDOWNLIST SELECTED VALUE.
    Protected Sub DropDown_Changed(sender As Object, e As EventArgs)
        Dim ddl As DropDownList = DirectCast(sender, DropDownList)
        ViewState("QTY") = ddl.Text
    End Sub

    Protected Sub LinkClicked(ByVal sender As Object, ByVal e As EventArgs)
        Dim lnk As LinkButton = DirectCast(sender, LinkButton)
        If Trim(lnk.ID) <> "" Then

            ' UPDATE QANITITY FOR THE SELECTED PRODUCT.
            Dim sUpdate As String = ""
            sUpdate = "UPDATE dbo.Stock SET Quantity = " & ViewState("QTY") & _
                " WHERE Product = '" & Trim(lnk.ID) & "'"

            ' UPDATE DATABASE CODE ...
        End If
    End Sub
End Class

Thanks for reading.

← PreviousNext →