Bind a DropDownList to a Database Table using GridView in Asp.Net C# and VB.Net

← PrevNext →

An Asp.Net DropDownList control holds a list of data, which allows the user to select a single data from a drop down list. We either use this as a standalone control on a web page or embed it in another control, like a GridView control.

Updated: I have added code in C# and Vb to save the selected Dropdownlist Data to a database table.

Dropdownlist

There are two ways you can insert values in a DropDownList. Insert the values at design time (that is manually) or you can the dynamically bind a DropDownList with a database table, using code behind procedure. How you are going to it, is totally your decision.

Insert Values in a DropDownList at Design Time (Manually)

<asp:DropDownList runat="server">
    <asp:ListItem>ADVANCE PHYSICS</asp:ListItem>
    <asp:ListItem>GRADUATE</asp:ListItem>
</asp:DropDownList>

However, in this article, I am going to show you how to bind a DropDownList to a database table, and later add the DropDownList to a GridView control. The GridView (in the demo) will display Employee details fetched from the database table.

Scenario

Here is a scenario. The user wants to alter the Qualification of an Employee by selecting a qualification from the drop down list. Therefore, I'll add a column named Qualification to the GridView, which will have a DropDownList. The DropDownList will get its data from a master table in the database.

SQL Server table "Qualification"

First, we need to create a table named dbo.Qualification in our SQL Server database. Add few rows of data in it.

CREATE TABLE dbo.Qualification
    (QualificationCode int NOT NULL, 
    Qualification VARCHAR(20) NULL,
	CONSTRAINT PK_Master_Qualification PRIMARY KEY CLUSTERED
	(QualificationCode ASC)) ON[PRIMARY]

-- ADD FEW ROWS IN THE TABLE.
INSERT INTO Qualification (QualificationCode, Qualification) 
    VALUES (1, 'GRADUATE')
INSERT INTO Qualification (QualificationCode, Qualification) 
    VALUES (2, 'ADVANCE PHYSICS')
INSERT INTO Qualification (QualificationCode, Qualification) 
    VALUES (3, 'DIPLOMA IN FINANCE')
INSERT INTO Qualification (QualificationCode, Qualification) 
    VALUES (4, 'MATHEMATICS')
INSERT INTO Qualification (QualificationCode, Qualification) 
    VALUES (5, 'ACCOUNTS')
INSERT INTO Qualification (QualificationCode, Qualification) 
    VALUES (6, 'MANAGEMENT')

How the GridView will actually work?

The DropDownList will show up when the user clicks the Edit button on a GridView row. If the row already has a qualification, then the value selected becomes the default (selected) value in the drop down list.

Showing Employee Details in Asp.Net DropDownList Control

image 1

Bind DropDownList in a GridView Control

image 2

The above images will give you some a idea about what I am trying to explain. In the first image, employee Arun Banik's qualification is MATHEMATICS. Clicking the Edit button will show the DropDownList with the default value as MATHEMATICS (See image 2).

Surely, the best way to understand this is to try the real demo.

Note: Add a connection string in the Web.Config file inside the <configuration> tag. The Web.Config file is automatically created when you create a New Web Site using the Visual Studio.

<connectionStrings>
    <add name="DNA_DB" connectionString="Data Source=DNA;Persist Security Info=False;
        Integrated Security=SSPI; Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=dna;
        Connect Timeout=30;"/>
</connectionStrings>
The Markup
<!DOCTYPE html>
<html>
<head>
    <title>Bind Data to a DropDownList in GridView</title>
    <style type="text/css">
        .dropdown { 
            font:12px/0.8 Arial; 
            border:solid 1px #6FA602; 
            border-radius:4px; 
            -moz-border-radius:4px; 
            -webkit-border-radius:4px; 
            cursor:pointer; 
            width:auto;
        }
        .gridv th,td { padding:5px }
    </style>
</head>

<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView
                ID = "GridView" 
                runat = "server" 
                AutoGenerateColumns = "False" 
                AutoGenerateEditButton = "True" 
                OnRowDataBound = "GridView_RowDataBound" 
                OnRowEditing = "GridView_RowEditing" 
                OnRowCancelingEdit = "GridView_RowCancelingEdit"
                OnRowUpdating = "GridView_RowUpdating"
                CssClass= "gridv">
                
        <Columns>
            <asp:TemplateField HeaderText="Employee ID"> 
                <ItemTemplate>
                    <asp:Label ID="lblEmpID" runat="server" Text='<% #Eval("EmpID") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
                    
            <asp:TemplateField HeaderText ="Employee Name">
                <ItemTemplate >
                    <asp:Label ID="lblEmpName" runat ="server" Text='<%#Eval("EmpName")%>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
                    
            <asp:TemplateField HeaderText="Qualification">
                <EditItemTemplate>
                    <%--Set AutoPostBack as true, to do a post back 
                        after selecting a new value from dropdown.--%>
                    <asp:DropDownList
                        id="ddlQualification" 
                        CssClass="dropdown" 
                        AutoPostBack="true" 
                        EnableViewState="true"
                        OnSelectedIndexChanged="getNewItem" 
                        runat="server">
                    </asp:DropDownList>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblqual" runat="server" Text='<% #Bind("Qualification") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
                
        <HeaderStyle
            BackColor="#989898" 
            BorderColor="Gray" 
            Font-Bold="True" 
            ForeColor="White" 
            Height="20px" />
                    
        <RowStyle HorizontalAlign="Center" Height="20px" />

            </asp:GridView>
        </div>
    </form>
</body>
</html>

Also Read: How to perform Edit and Delele operations using GridView in Asp.Net

Code Behind (C# Example)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;                  // For DataTable.
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page 
{
    SqlConnection myConn = default(SqlConnection);
    SqlCommand sqComm = default(SqlCommand);

    System.Data.DataSet ds = new System.Data.DataSet();
    System.Data.SqlClient.SqlDataAdapter SqlAdapter;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (setConn())
        {
            PopulateDataSet();       // Fill DataSet with master data.

            if (!IsPostBack)
            {
                ShowEmpDetails();   // Show employee details in the GridView.
            }
        }
    }

    private bool setConn()
    {
        // Set database connection.
        try
        {
            myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DNA_DB"].ConnectionString);
            myConn.Open();

            sqComm = new SqlCommand();
            sqComm.Connection = myConn;
        }
        catch (Exception ex) { return false; }
        return true;
    }

    // Cancle row editing.
    protected void GridView_RowCancelingEdit(object sender, _
        System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
    {
        GridView.EditIndex = -1;
        ShowEmpDetails();
    }

    protected void GridView_RowDataBound(object sender, 
        System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        if ((e.Row.RowState & DataControlRowState.Edit) > 0)
        {
            // Bind the DropDownList with the DataSet field with "Qualification" details.
            DropDownList ddlQual = new DropDownList();
            ddlQual = (DropDownList)e.Row.FindControl("ddlQualification");

            if (ddlQual != null)
            {
                ddlQual.DataSource = ds.Tables["qual"];
                ddlQual.DataTextField = ds.Tables["qual"].Columns["Qualification"].ColumnName.ToString();
                ddlQual.DataValueField = ds.Tables["qual"].Columns["QualificationCode"].ColumnName.ToString();
                ddlQual.DataBind();

                // Assign the seleted row value (Qalification Code) to the DropDownList selected value.
                ((DropDownList)e.Row.FindControl("ddlQualification")).SelectedValue = 
                    DataBinder.Eval(e.Row.DataItem, "QualificationCode").ToString();
            }
        }
    }

    protected void GridView_RowEditing(object sender System.Web.UI.WebControls.GridViewEditEventArgs e)
    {
        GridView.EditIndex = e.NewEditIndex;
        ShowEmpDetails();
    }

    // Save dropdown value in database table.
    protected void GridView_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
    {
        // Get the Employee id from the active GridView row.
        Label iEmpId = (Label)(GridView.Rows[e.RowIndex].Cells[1].Controls[1]);

        string sQuery;
        sQuery = "UPDATE EmployeeDetails SET Qualification = '" + ViewState["newQualification"] + "' " + 
            "WHERE EmpID = " + iEmpId.Text;

        using (SqlCommand cmd = new SqlCommand(sQuery))
        {
            {
                var withBlock = cmd;
                withBlock.Connection = myConn;
                withBlock.ExecuteNonQuery();
            }
        }

        GridView.EditIndex = -1;     // Set EditIndex = -1 to come out of Edit mode after update.
        ShowEmpDetails();
    }

     // Master data in a DataSet.
    private void PopulateDataSet()
    {
        ds.Clear();
        SqlAdapter = new System.Data.SqlClient.SqlDataAdapter
            ("SELECT QualificationCode, Qualification FROM dbo.Qualification", myConn);

        SqlAdapter.Fill(ds, "qual");
        SqlAdapter.Dispose();
    }

    // Get employee details.
    private void ShowEmpDetails()
    {
        string sQuery = "SELECT EmpDet.EmpID, EmpDet.EmpName, 
            EmpDet.Qualification, Qual.QualificationCode " + 
            "FROM dbo.EmployeeDetails EmpDet " + 
            "LEFT OUTER JOIN Qualification Qual ON EmpDet.Qualification = Qual.Qualification";
        
        SqlDataReader sdrEmp = GetDataReader(sQuery);
        try 
        {
            if (sdrEmp.HasRows) {
                DataTable dt = new DataTable();
                dt.Load(sdrEmp);

                GridView.DataSource = dt;
                GridView.DataBind();    // Bind database table with the GridView.
            }
        } 
        catch (Exception ex) { }
        finally 
        {
            sdrEmp.Close();
            sdrEmp = null;
        }
    }
    private SqlDataReader GetDataReader(string sQuery)
    {
        SqlDataReader functionReturnValue = default(SqlDataReader);
        sqComm.CommandText = sQuery;
        sqComm.ExecuteNonQuery();
        functionReturnValue = sqComm.ExecuteReader();
        sqComm.Dispose();
        return functionReturnValue;
    }
}
Visual Basic (Example)
Option Explicit On
Imports System.Data             ' For DataTable.
Imports System.Data.SqlClient

Partial Class _Default
    Inherits System.Web.UI.Page

    Dim myConn As SqlConnection
    Dim sqComm As SqlCommand

    Dim ds As New Data.DataSet
    Dim SqlAdapter As System.Data.SqlClient.SqlDataAdapter

    Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
        If setConn() Then
            PopulateDataSet()           ' Fill DataSet with master data.

            If Not IsPostBack Then
                ShowEmpDetails()        ' Show employee details in the GridView.
            End If
        End If
    End Sub

    Private Function setConn() As Boolean
        ' Set database connection.
        Try
            myConn = New SqlConnection("Data Source=DNA;
                Persist Security Info=False;Integrated Security=SSPI;" & _
                "Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=;Connect Timeout=30;")

            myConn.Open()

            sqComm = New SqlCommand
            sqComm.Connection = myConn
        Catch ex As Exception
            Return False
        End Try
        Return True
    End Function

    ' Cancel row editing.
    Protected Sub GridView_RowCancelingEdit(ByVal sender As Object, _
        ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) _
        Handles GridView.RowCancelingEdit
            
        GridView.EditIndex = -1
        ShowEmpDetails()
    End Sub

    Protected Sub GridView_RowDataBound(ByVal sender As Object, _
        ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
        Handles GridView.RowDataBound

        If (e.Row.RowState And DataControlRowState.Edit) > 0 Then

            ' Bind the DropDownList with the DataSet field with "Qualification" details.
            Dim ddlQual As New DropDownList
            ddlQual = e.Row.FindControl("ddlQualification")

            If Not IsDBNull(ddlQual) Then
                With ddlQual
                    .DataSource = ds.Tables("qual")
                    .DataTextField = ds.Tables("qual").Columns("Qualification").ColumnName.ToString()
                    .DataValueField = ds.Tables("qual").Columns("QualificationCode").ColumnName.ToString()
                    .DataBind()

                    ' Assign the seleted row value (Qalification Code) to the DropDownList selected value.
                    CType(e.Row.FindControl("ddlQualification"), DropDownList).SelectedValue = _
                        DataBinder.Eval(e.Row.DataItem, "QualificationCode").ToString()
                End With
            End If
        End If
    End Sub

    ' Save dropdown value in database table.
    Protected Sub GridView_RowUpdating(sender As Object, _
        e As System.Web.UI.WebControls.GridViewUpdateEventArgs) _
        Handles GridView.RowUpdating

        ' Get the Employee id from the active GridView row.
        Dim iEmpId As Integer = TryCast(GridView.Rows(e.RowIndex).Cells(1).Controls.Item(1), Label).Text

        Dim sQuery As String
        sQuery = "UPDATE EmployeeDetails SET Qualification = '" & Trim(ViewState("newQualification")) & "' " & _
            "WHERE EmpID = " & iEmpId

        Using cmd As SqlCommand = New SqlCommand(sQuery)
            With cmd
                .Connection = myConn
                .ExecuteNonQuery()
            End With
        End Using

        GridView.EditIndex = -1     ' Set EditIndex = -1 to come out of Edit mode after update.
        ShowEmpDetails()
    End Sub

    ' Row editing.
    Protected Sub GridView_RowEditing(ByVal sender As Object, _
        ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView.RowEditing
            
        GridView.EditIndex = e.NewEditIndex
        ShowEmpDetails()
    End Sub

    ' Master data in a DataSet.
    Private Sub PopulateDataSet()
        ds.Clear()

        SqlAdapter = New System.Data.SqlClient.SqlDataAdapter( _
            "SELECT QualificationCode, Qualification FROM dbo.Qualification", myConn)
        SqlAdapter.Fill(ds, "qual")

        SqlAdapter.Dispose()
    End Sub

    ' Get employee details.
    Private Sub ShowEmpDetails()
        Dim sQuery As String = "SELECT EmpDet.EmpID, EmpDet.EmpName, EmpDet.Qualification, " & _
            "Qual.QualificationCode FROM dbo.EmployeeDetails EmpDet " & _
            "LEFT OUTER JOIN Qualification Qual ON EmpDet.Qualification = Qual.Qualification"
        Dim sdrEmp As SqlDataReader = GetDataReader(sQuery)
        Try
            If sdrEmp.HasRows Then
                Dim dt As New DataTable
                dt.Load(sdrEmp)

                ' Bind database table with the GridView.
                GridView.DataSource = dt : GridView.DataBind()
            End If
        Catch ex As Exception
        Finally
            sdrEmp.Close() : sdrEmp = Nothing
        End Try
    End Sub

    Private Function GetDataReader(Optional ByVal sQuery As String = "") As SqlDataReader
        sqComm.CommandText = sQuery
        sqComm.ExecuteNonQuery()
        GetDataReader = sqComm.ExecuteReader
        sqComm.Dispose()
    End Function
End Class

If you want the source code, mail me. You can find my email id at the bottom of this blog. Thanks for reading.

← PreviousNext →