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

← PrevNext →

Enhance your ASP.NET GridView by adding or binding a DropDownList to each cell using its built-in functions. I've previously shared a simple example, be sure to check out this post for reference. Additionally, you can dynamically create and add a DropDownList to the GridView based on specific conditions, allowing for greater flexibility. In this guide, I'll also demonstrate how to attach an event to the dynamically generated DropDownList to capture selected values effectively.

C# example

VB.Net example

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

See this demo

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".

<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");

                ViewState["QTY"] = ddl.SelectedValue;     // assign default value to viewstate.
                
                // 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 ...
        }
    }
}

➡️ GridView examples

Don't be intimidated by the length of the code. The key function to focus on is GridView_RowDataBound, where I dynamically create and add a DropDownList to the grid.

I have created and populated the "grid" with some values. I am also using the DataTable class and its properties to create the grid, add columns and finally add rows to the grid.

During the GridView's row binding process, the RowDataBound event fires. Within this event, I check whether the first cell—the 'Stock' column—indicates that the item is out-of-stock. If it does, I dynamically create a DropDownList and insert it into the blank final cell of the grid.

If you have noticed, I have created a LinkButton dynamically. This is optional. Both 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 an event when you change the value in the DropDownList and click the LinkButton.

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;
}
See this demo
Code Behind (VB.NET)

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

← PreviousNext →