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 EventArgs) Handles 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 SqlCommand) As 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
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
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
Post a Comment