In this article I will explain with an example, how to use ASP.Net DropDownList control in the EditItemTemplate of ASP.Net GridView control using C# and VB.Net.
This article will explain how to set the previously saved value in DropDownList selected value.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
HTML Markup
Following HTML Markup consists of an ASP.Net GridView control. 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:DropDownList ID="ddlCities" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Populating the GridView
Inside the Page Load event of the page, the GridView is populated from database using the BindGrid method.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string sql = "SELECT TOP 10 CustomerID, ContactName, City FROM Customers";
string conString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter(sql, con))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim sql As String = "SELECT TOP 10 CustomerID, ContactName, City FROM Customers"
Dim conString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Using con As SqlConnection = New SqlConnection(conString)
Using sda As SqlDataAdapter = New SqlDataAdapter(sql, con)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
gvCustomers.DataSource = dt
gvCustomers.DataBind()
End Using
End Using
End Using
End Sub
Binding the DropDownList in GridView
Inside the OnRowDataBound event handler, first the DropDownList control is referenced and then it is populated using distinct values of Cities from the Customers table.
Finally, the selected City is set in the 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 sql = "SELECT DISTINCT City FROM Customers";
string conString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter(sql, con))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
ddlCities.DataSource = dt;
ddlCities.DataTextField = "City";
ddlCities.DataValueField = "City";
ddlCities.DataBind();
string selectedCity = DataBinder.Eval(e.Row.DataItem, "City").ToString();
ddlCities.Items.FindByValue(selectedCity).Selected = true;
}
}
}
}
}
VB.Net
Protected Sub RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow AndAlso gvCustomers.EditIndex = e.Row.RowIndex Then
Dim ddlCities As DropDownList = CType(e.Row.FindControl("ddlCities"), DropDownList)
Dim sql As String = "SELECT DISTINCT City FROM Customers"
Dim conString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Using con As SqlConnection = New SqlConnection(conString)
Using sda As SqlDataAdapter = New SqlDataAdapter(sql, con)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
ddlCities.DataSource = dt
ddlCities.DataTextField = "City"
ddlCities.DataValueField = "City"
ddlCities.DataBind()
Dim selectedCity As String = DataBinder.Eval(e.Row.DataItem, "City").ToString()
ddlCities.Items.FindByValue(selectedCity).Selected = True
End Using
End Using
End Using
End If
End Sub
Editing the GridView Row
When the Edit Button is clicked, the GridView’s OnRowEditing event handler is triggered.
The EditIndex of the GridView is updated with the RowIndex of the GridView Row being edited and the GridView is again populated with data.
C#
protected void EditCustomer(object sender, GridViewEditEventArgs e)
{
gvCustomers.EditIndex = e.NewEditIndex;
this.BindGrid();
}
VB.Net
Protected Sub EditCustomer(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
gvCustomers.EditIndex = e.NewEditIndex
Me.BindGrid()
End Sub
Canceling the Edit
When the Cancel Button is clicked, the GridView’s OnRowCancelingEdit event handler is triggered.
The EditIndex is set to -1 and the GridView is again populated with data.
C#
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gvCustomers.EditIndex = -1;
this.BindGrid();
}
VB.Net
Protected Sub CancelEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
gvCustomers.EditIndex = -1
Me.BindGrid()
End Sub
Updating the GridView Row
When the Update Button is clicked, the GridView’s OnRowUpdating event handler is triggered.
The value of the CustomerId is fetched from the DataKeyNames property and the value of the City is fetched from the DropDownList.
Finally, these values are updated in the Database table and the GridView is again populated with data.
C#
protected void UpdateCustomer(object sender, GridViewUpdateEventArgs e)
{
string city = (gvCustomers.Rows[e.RowIndex].FindControl("ddlCities") as DropDownList).SelectedItem.Value;
string customerId = gvCustomers.DataKeys[e.RowIndex].Value.ToString();
string conString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
string query = "UPDATE Customers SET City = @City WHERE CustomerId = @CustomerId";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@CustomerId", customerId);
cmd.Parameters.AddWithValue("@City", city);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
VB.Net
Protected Sub UpdateCustomer(ByVal sender As Object, ByVal 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 conString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Using con As SqlConnection = New SqlConnection(conString)
Dim query As String = "UPDATE Customers SET City = @City WHERE CustomerId = @CustomerId"
Using cmd As SqlCommand = New SqlCommand(query, con)
cmd.Parameters.AddWithValue("@CustomerId", customerId)
cmd.Parameters.AddWithValue("@City", city)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Response.Redirect(Request.Url.AbsoluteUri)
End Using
End Using
End Sub
Screenshot
Downloads