In this article I will explain with an example, how to populate
DropDownList with selected value in
EditItemTemplate of
GridView in ASP.Net using C# and VB.Net.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The HTML Markup consists of following controls:
GridView – For displaying data.
Columns
The
GridView consists of one
BoundField column, one
TemplateField column and one
CommandField column.
TemplateField – The TemplateField column consists of ItemTemplate and EditItemTemplate.
ItemTemplate – The ItemTemplate consists of a Label.
EditItemTemplate – The
EditItemTemplate consists of a
DropDownList.
The
GridView has been assigned with the following property:
DataKeyNames – For permitting to set the names of the Column Fields, that we want to use in code but do not want to display it. Example Primary Keys, ID fields, etc.
The
GridView has been assigned with the following event handlers i.e.
OnRowEditing,
OnRowDataBound,
OnRowUpdating and
OnRowCancelingEdit.
The CommandField column has been assigned with the following property:
ShowEditButton – For displaying Edit LinkButton.
<asp:GridView ID="gvCustomers" DataKeyNames="CustomerId" runat="server" AutoGenerateColumns="false"
OnRowEditing="OnRowEditing" OnRowDataBound="OnRowDataBound" OnRowUpdating="OnRowUpdating"
OnRowCancelingEdit="OnRowCancelingEdit">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCountry" 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 handler, the
BindGrid method is called where the records are fetched from the
Customers Table of the
SQL Server database and the
GridView is populated.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string sql = "SELECT CustomerId, Name, Country FROM Customers";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
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 CustomerId, Name, Country FROM Customers"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
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 using C# and VB.Net
Inside the OnRowDataBound event handler, a check is performed whether the selected row is DataRow and it is in edit mode.
Then, the
DropDownList control is referenced and it is populated using
DISTINCT values of Country from the
Customers Table.
The Text and Value properties are set and country is selected using Eval method of DataBinder class.
Finally, the selected Country is set in the
DropDownList control and made selected.
C#
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvCustomers.EditIndex == e.Row.RowIndex)
{
DropDownList ddlCountry = (DropDownList)e.Row.FindControl("ddlCountry");
string sql = "SELECT DISTINCT Country FROM Customers";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter(sql, con))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
ddlCountry.DataSource = dt;
ddlCountry.DataTextField = "Country";
ddlCountry.DataValueField = "Country";
ddlCountry.DataBind();
string selectedCountry = DataBinder.Eval(e.Row.DataItem, "Country").ToString();
ddlCountry.Items.FindByValue(selectedCountry).Selected = true;
}
}
}
}
}
VB.Net
Protected Sub OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow AndAlso gvCustomers.EditIndex = e.Row.RowIndex Then
Dim ddlCountry As DropDownList = CType(e.Row.FindControl("ddlCountry"), DropDownList)
Dim sql As String = "SELECT DISTINCT Country FROM Customers"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter(sql, con)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
ddlCountry.DataSource = dt
ddlCountry.DataTextField = "Country"
ddlCountry.DataValueField = "Country"
ddlCountry.DataBind()
Dim selectedCountry As String = DataBinder.Eval(e.Row.DataItem, "Country").ToString()
ddlCountry.Items.FindByValue(selectedCountry).Selected = True
End Using
End Using
End Using
End If
End Sub
Editing in GridView
When the
Edit Button is clicked, the
EditIndex of the
GridView is updated with the
RowIndex of the GridViewRow being edited and the
GridView is again populated with data.
C#
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
gvCustomers.EditIndex = e.NewEditIndex;
this.BindGrid();
}
VB.Net
Protected Sub OnRowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
gvCustomers.EditIndex = e.NewEditIndex
Me.BindGrid()
End Sub
Canceling the Edit in GridView
When the Cancel Button is clicked, the EditIndex is set to -1 and the GridView is again populated with data.
C#
protected void OnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvCustomers.EditIndex = -1;
this.BindGrid();
}
VB.Net
Protected Sub OnRowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
gvCustomers.EditIndex = -1
Me.BindGrid()
End Sub
Updating the GridView
When the
Update Button is clicked, the
CustomerId (primary key) is fetched from the
DataKeys property of
GridView and
Country is fetched from the
DropDownList Control.
Finally, these values are updated in the
SQL Server database using
ExecuteNonQuery method.
C#
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
string country = (gvCustomers.Rows[e.RowIndex].FindControl("ddlCountry") as DropDownList).SelectedItem.Value;
string customerId = gvCustomers.DataKeys[e.RowIndex].Value.ToString();
string sql = "UPDATE Customers SET Country = @Country WHERE CustomerId = @CustomerId";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("@CustomerId", customerId);
cmd.Parameters.AddWithValue("@Country", country);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
VB.Net
Protected Sub OnRowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
Dim country As String = (TryCast(gvCustomers.Rows(e.RowIndex).FindControl("ddlCountry"), DropDownList)).SelectedItem.Value
Dim customerId As String = gvCustomers.DataKeys(e.RowIndex).Value.ToString()
Dim sql As String = "UPDATE Customers SET Country = @Country WHERE CustomerId = @CustomerId"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("@CustomerId", customerId)
cmd.Parameters.AddWithValue("@Country", country)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Response.Redirect(Request.Url.AbsoluteUri)
End Using
End Using
End Sub
Screenshot
Downloads