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

GRIDVIEW GROUPING

When displaying data, we sometimes would like to group data for better user experience or when displaying long list of hierarchal data, we would want to display them in a tree view kind of structure. There is more than way of doing this, but I am going to explain achieving this functionality using  AJAX Collapsible Panel Extender Control . Overview: I am going to use  Adventure Works  as datasource. Every product in  Production.Product  table belongs to a product sub category. We fetch handful of products and the sub categories they belong to from the database. Our objective is to list all the available sub categories and allow user to  expand/collapse  to look/hide the list of products belonging to each subcategory. Database Connection Added following entry under  connectionStrings  element in  web.config . < add   name = "Sql"   connectionString="Data Source=(local); Initial  Catalog = AdventureWorks ...

ADO.NET Concepts With example

COMMAND OBJECT  Command object is the biggest object in ADO.NET  It is the only object which can perform actions with database  It  can be created directly using Command class or can be created using Connection.Create command (factory classes also contain creation of Command). Ex:  SqlConnection sqlCon = new SqlConnection("......");    SqlCommand sqlCmd = sqlCon.CreateCommand();  Commands that we run depend upon the kind of query that we want to execute with database. All databases support two types of queries. i. Action Queries ii. Non-action Queries Action queries are those which change the state of database and which don‟t return any query results(though they return the number of records affected). Ex: Insert, Delete and Update statements Non-action queries are those which don‟t affect the database but return the results to the user. Ex: Select statement Method of execution of queries: Command object provides the following methods to execute queries: 1. Ex...

GRIDVIEW ZOOM IMAGE

When you have images in your  GridView , you would most likely show them as thumbnails so as to not distort the whole layout. However user would want to look at the full image by clicking on the image or just hovering his mouse over it. In today’s applications, this is a basic requirement and there are just so many third party controls or plugins which would support this functionality. I am going do this conventional way using  javascript  way in this article.  On top of it, I am also going to explain how to get images from database using  HttpHandlers . Example: I am using  Adventure Works  as datasource. We fetch handful of products and bind them to the grid. When page is initially loaded, we retrieve products from Production . Product  table and bind them to the grid. We display some product attributes such as Product ID, Product Number, Product Name, List Price and product’s thumbnail. When user hover his mouse on the page, we fetch the f...