Skip to main content

Populate DropDownList with Selected Value in EditItemTemplate of GridView in ASP.Net


Database and Connection string
For this article as usual I have used my favorite NorthWind database which you can get by clicking on the link below.
Below is the connection string from the Web.Config file
<connectionStrings>
<addname="conString"connectionString="Data Source=.\SQLExpress;
database=Northwind;Integrated Security=true"/>
</connectionStrings>
 
GridView Markup
Below I have a simple GridView ASP.Net GridView control populated from the Customers table of Northwind database. It displays 2 columns Contact Name and City of which city is editable via ASP.Net DropDownList control. The identifier column Customer Id is bind to the DataKeyNames property.
<asp:GridView ID="gvCustomers" DataKeyNames = "CustomerId" runat="server" AutoGenerateColumns = "false"OnRowEditing = "EditCustomer" OnRowDataBound = "RowDataBound" OnRowUpdating = "UpdateCustomer"OnRowCancelingEdit = "CancelEdit">
<Columns>
    <asp:BoundField DataField = "ContactName" HeaderText = "Contact Name" />
    <asp:TemplateField HeaderText = "City">
    <ItemTemplate>
        <asp:Label ID="lblCity" runat="server" Text='<%# Eval("City")%>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
            <asp:Label ID="lblCity" runat="server" Text='<%# Eval("City")%>' Visible = "false"></asp:Label>
    <asp:DropDownList ID = "ddlCities" runat = "server">
    </asp:DropDownList>
    </EditItemTemplate>
    </asp:TemplateField>
    <asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
 
Binding the GridView
Below is the code to Bind the GridView control with data.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.BindData();
    }
}
 
private void BindData()
{
    string query = "SELECT top 10 * FROM Customers";
    SqlCommand cmd = new SqlCommand(query);
    gvCustomers.DataSource = GetData(cmd);
    gvCustomers.DataBind();
}
 
private DataTable GetData(SqlCommand cmd)
{
    string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            using (DataTable dt = new DataTable())
            {
                sda.Fill(dt);
                return dt;
            }
        }
    }
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgsHandles Me.Load
   If Not IsPostBack Then
       Me.BindData()
   End If
End Sub
 
Private Sub BindData()
   Dim query As String = "SELECT top 10 * FROM Customers"
   Dim cmd As New SqlCommand(query)
   gvCustomers.DataSource = GetData(cmd)
   gvCustomers.DataBind()
End Sub
 
Private Function GetData(cmd As SqlCommandAs DataTable
   Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
   Using con As New SqlConnection(strConnString)
       Using sda As New SqlDataAdapter()
           cmd.Connection = con
          sda.SelectCommand = cmd
           Using dt As New DataTable()
               sda.Fill(dt)
               Return dt
           End Using
       End Using
  End Using
End Function
 
Screenshot
Below is the screenshot of GridView with data
Binding the GridView with DropDownList in ASP.Net

Editing the GridView Row
The below events handle the GridView Row Edit and Cancel Edit Events
C#
protected void EditCustomer(object sender, GridViewEditEventArgs e)
{
    gvCustomers.EditIndex = e.NewEditIndex;
    BindData();
}
 
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
    gvCustomers.EditIndex = -1;
    BindData();
}
 
VB.Net
Protected Sub EditCustomer(sender As Object, e As GridViewEditEventArgs)
    gvCustomers.EditIndex = e.NewEditIndex
    Me.BindData()
End Sub
 
Protected Sub CancelEdit(sender As Object, e As GridViewCancelEditEventArgs)
    gvCustomers.EditIndex = -1
    BindData()
End Sub
 
Binding the DropDownList
The DropDownList has to be bind in the RowDataBound event of the ASP.Net GridView control in the following way. I have kept an invisible Label in order to get the previously stored City.
C#
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow && gvCustomers.EditIndex == e.Row.RowIndex)
    {
        DropDownList ddlCities = (DropDownList)e.Row.FindControl("ddlCities");
        string query = "select distinct city from customers";
        SqlCommand cmd = new SqlCommand(query);
        ddlCities.DataSource = GetData(cmd);
        ddlCities.DataTextField = "city";
        ddlCities.DataValueField = "city";
        ddlCities.DataBind();
        ddlCities.Items.FindByValue((e.Row.FindControl("lblCity"as Label).Text).Selected = true;
    }
}
 
VB.Net
Protected Sub RowDataBound(sender As Object, e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow AndAlso gvCustomers.EditIndex = e.Row.RowIndex Then
      Dim ddlCities As DropDownList = DirectCast(e.Row.FindControl("ddlCities"), DropDownList)
      Dim query As String = "select distinct city from customers"
      Dim cmd As New SqlCommand(query)
      ddlCities.DataSource = GetData(cmd)
      ddlCities.DataTextField = "city"
      ddlCities.DataValueField = "city"
      ddlCities.DataBind()
      ddlCities.Items.FindByValue(TryCast(e.Row.FindControl("lblCity"), Label).Text).Selected = True
    End If
End Sub
 
Screenshot
The below screenshot displays the GridView with row being edited
Binding the GridView with DropDownList in EditItemTemplate in ASP.Net

Updating the GridView Row
Finally here’s the code to update the record with the new selected value from the ASP.Net DropDownList control.
C#
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow && gvCustomers.EditIndex == e.Row.RowIndex)
    {
        DropDownList ddlCities = (DropDownList)e.Row.FindControl("ddlCities");
        string query = "select distinct city from customers";
        SqlCommand cmd = new SqlCommand(query);
        ddlCities.DataSource = GetData(cmd);
        ddlCities.DataTextField = "city";
        ddlCities.DataValueField = "city";
        ddlCities.DataBind();
        ddlCities.Items.FindByValue((e.Row.FindControl("lblCity"as Label).Text).Selected = true;
    }
}
 
VB.Net
Protected Sub UpdateCustomer(sender As Object, e As GridViewUpdateEventArgs)
    Dim city As String = TryCast(gvCustomers.Rows(e.RowIndex).FindControl("ddlCities"),DropDownList).SelectedItem.Value
    Dim customerId As String = gvCustomers.DataKeys(e.RowIndex).Value.ToString()
    Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
    Using con As New SqlConnection(strConnString)
        Dim query As String = "update customers set city = @city where customerId = @customerId"
        Using cmd As New SqlCommand(query)
            cmd.Connection = con
            cmd.Parameters.AddWithValue("@city", city)
            cmd.Parameters.AddWithValue("@customerId", customerId)
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
            Response.Redirect(Request.Url.AbsoluteUri)
        End Using
    End Using
End Sub
 
Downloads
You can download the full source code of this article in C# and VB.Net using the download link provided below.
DropdownlistinEditItemTemplateGridView.zip
 

Comments

Popular posts from this blog

Editing Child GridView in Nested GridView

Editing Child GridView in Nested GridView In this article we will explore how to edit child gridview in the nested gridview.   Let''s write some code. Step 1:  Add scriptmanager in the aspx page. < asp : ScriptManager   ID ="ScriptManager1"   runat ="server"   EnablePageMethods ="true"> </ asp : ScriptManager > Step 2:  Add below stylesheet for modal popup. < style   type ="text/css">        .modalBackground        {              background-color : Gray;              filter : alpha(opacity=80);              opacity : 0.5;       }        .ModalWindow        {              border : solid1px#c0c0c0;              background : #f0f0f0;              padding : 0px10px10px10px;              position : absolute;              top : -1000px;       } </ style > Step 3:   Create an aspx page and add a Gridview with another gridview in the last TemplateField. The last templatefield will also contain a lable which will

Nested GridView Example In Asp.Net With Expand Collapse

This example shows how to create Nested GridView In Asp.Net Using C# And VB.NET With Expand Collapse Functionality. I have used JavaScript to Create Expandable Collapsible Effect by displaying Plus Minus image buttons. Customers and Orders Table of Northwind Database are used to populate nested GridViews. Drag and place SqlDataSource from toolbox on aspx page and configure and choose it as datasource from smart tags Go to HTML source of page and add 2 TemplateField in <Columns>, one as first column and one as last column of gridview. Place another grid in last templateField column. Markup of page after adding both templatefields will like as shown below. HTML SOURCE 1: < asp:GridView ID ="gvMaster" runat ="server" 2: AllowPaging ="True" 3: AutoGenerateColumns ="False" 4: DataKeyNames ="CustomerID" 5: DataSour

Add Edit Update Records in GridView using Modal Popup in ASP.Net

Add Edit Update Records in GridView using Modal Popup in ASP.Net In this article, I’ll explain how to Add and Edit records in ASP.Net GridView control using ASP.Net AJAX Control Toolkit Modal Popup Extender. Database For this tutorial, I am using Microsoft’s NorthWind database. You can download it using the following link. Download Northwind Database Connection string Below is the connection string to connect to the database. < connectionStrings >     < add name = " conString "      connectionString = " Data Source=.\SQLExpress;database=Northwind;     Integrated Security=true " /> </ connectionStrings >   HTML Markup Below is the HTML Markup of the page. Below you will notice that I have placed a Script Manager and an ASP.Net Update Panel on the page. Inside the Update Panel I have placed an ASP.Net GridView Control along with a Modal Popup Extender that will be used to Add or Edit the records in the GridView