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

Hierarchical GridView in ASP.NET with AJAX, JQuery implementation - Part 1

Previously I had blogged some post related to showing two grids in hierarchical way. For example - when I need to show an invoice reports on the screen, the user requesting to show the list of invoices at initial time and they can drill down the details of item details of each invoice by clicking on respective row. The implementations can be in multiple ways, but I had blogged the implementation with AJAX and without AJAX using Java script on ASP.NET page. Below are the URLs of the same – Hierarchical GridView in ASP.NET Hierarchical GridView in ASP.NET with AJAX, Javascript implementation In this post I am taking the same requirements done before and enhance with some additional functionality as per readers expectations. The requirement on this implementation will be – The page should show a Grid View with list of Orders with Expand icon on the first column. On click of expand icon on each row, the Order Details of the Order must be fetched from the database

Scrollable Gridview With fixheader using JQuery in Asp.net

Scrollable Gridview With fixheader using JQuery in Asp.net Introduction: In this article I will explain how to implement scrollable gridview with fixed header in asp.net using JQuery.  Description:  In Previous posts I explained lot of articles regarding Gridview. Now I will explain how to implement scrollable gridview with fixed header in asp.net. I have one gridview that contains lot of records and I used  paging for gridview  but the requirement is to display all the records without paging. I removed paging at that time gridview occupied lot of space because it contains more records to solve this problem we implemented scrollbar.  After scrollbar implementation if we scroll the gridview we are unable to see Gridview header.   To implement Scrollable gridview with fixed header I tried to implement concept with css and JavaScript but there is no luck because maintaining fixed header working in IE but not in Mozilla and vice versa to solve this browser compatibility proble