In this article I will explain with an example, how to edit and update multiple rows in
GridView using CheckBoxes in
ASP.Net using C# and VB.Net.
The Rows which are checked will become editable and user can update multiple rows on single Update Button click.
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 three TemplateField columns.
TemplateField – First TemplateField column consists of HeaderTemplate and ItemTemplate.
HeaderTemplate – The HeaderTemplate contains a CheckBox.
ItemTemplate – The ItemTemplate contains a CheckBox.
The CheckBoxes have been assigned with an OnCheckedChanged event handler.
TemplateField – Second TemplateField column consists of ItemTemplate.
ItemTemplate – The ItemTemplate contains a Label and a TextBox control.
Label – For displaying Name value.
TextBox – For capturing Name value to be updated.
TemplateField – Third TemplateField column consists of ItemTemplate.
ItemTemplate – The ItemTemplate contains a Label and a DropDownList control.
Label – For displaying Country value.
DropDownList – For capturing Country value to be updated.
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.
Event
The
GridView has been assigned with an
OnRowDataBound event handler.
Button – For updating the record.
The Button has been assigned with an OnClick event handler.
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound" DataKeyNames="CustomerId">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Contact Name" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name")%>'></asp:Label>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name")%>' Visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country")%>'></asp:Label>
<asp:DropDownList ID="ddlCountries" runat="server" Visible="false"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="OnUpdate" Visible="false" />
Namespaces
You will need to import the following namespaces.
C#
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Linq
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Binding the ASP.Net 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 using
ExecuteQuery method.
Finally, the GridView is populated.
ExecuteQuery
Inside the ExecuteQuery method, the switch case statement is executed and if SELECT is the action then, records are fetched from database and DataTable is returned.
And if UPDATE is the action then, records are updated using ExecuteNonQuery method.
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";
using (SqlCommand cmd = new SqlCommand(sql))
{
gvCustomers.DataSource = this.ExecuteQuery(cmd, "SELECT");
gvCustomers.DataBind();
}
}
private DataTable ExecuteQuery(SqlCommand cmd, string action)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
cmd.Connection = con;
switch (action)
{
case "SELECT":
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
case "UPDATE":
con.Open();
cmd.ExecuteNonQuery();
con.Close();
break;
}
return null;
}
}
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"
Using cmd As SqlCommand = New SqlCommand(sql)
gvCustomers.DataSource = Me.ExecuteQuery(cmd, "SELECT")
gvCustomers.DataBind()
End Using
End Sub
Private Function ExecuteQuery(ByVal cmd As SqlCommand, ByVal action As String) As DataTable
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
cmd.Connection = con
Select Case action
Case "SELECT"
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
Case "UPDATE"
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Select
Return Nothing
End Using
End Function
Populating the Country DropDownList in the ASP.Net GridView Row
Inside the
OnRowDataBound event handler, a check is performed if selected row is
DataRow then, the
DropDownList is referenced and SELECT query is passed as parameter to
ExecuteQuery method and fetched records are used as DataSource of
DropDownList.
The
DataTextField,
DataValueField properties are set and
DropDownList is populated.
Finally, based on the Label value the DropDownList item is made selected using the FindByValue method.
C#
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
string sql = "SELECT DISTINCT(Country) FROM Customers";
if (e.Row.RowType == DataControlRowType.DataRow)
{
SqlCommand cmd = new SqlCommand(sql);
DropDownList ddlCountries = (e.Row.FindControl("ddlCountries") as DropDownList);
ddlCountries.DataSource = this.ExecuteQuery(cmd, "SELECT");
ddlCountries.DataTextField = "Country";
ddlCountries.DataValueField = "Country";
ddlCountries.DataBind();
string country = (e.Row.FindControl("lblCountry") as Label).Text;
ddlCountries.Items.FindByValue(country).Selected = true;
}
}
VB.Net
Protected Sub OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim sql As String = "SELECT DISTINCT(Country) FROM Customers"
If e.Row.RowType = DataControlRowType.DataRow Then
Dim cmd As SqlCommand = New SqlCommand(sql)
Dim ddlCountries As DropDownList = (TryCast(e.Row.FindControl("ddlCountries"), DropDownList))
ddlCountries.DataSource = Me.ExecuteQuery(cmd,"SELECT")
ddlCountries.DataTextField = "Country"
ddlCountries.DataValueField = "Country"
ddlCountries.DataBind()
Dim country As String = (TryCast(e.Row.FindControl("lblCountry"), Label)).Text
ddlCountries.Items.FindByValue(country).Selected = True
End If
End Sub
Switching the ASP.Net GridView Row to Edit mode on CheckBox checked
Inside the OnCheckedChanged event handler, first a Boolean variable is created and set to FALSE.
Next, the CheckBox is referenced and a check is performed if Check All CheckBox in the GridView Header Row is checked or unchecked then, a FOR EACH loop is executed over the GridView rows.
Again a check is performed if selected row is DataRow then, the CheckBox is made checked.
Then, the CheckBox of HeaderRow is referenced and FOR EACH loop is executed over GridView rows and Boolean variable value is set based on the state of CheckBox and the visibility of Label, TextBox and DropDownList is determined based on the Boolean value.
Finally, isUpdateVisible is set to the Visible property of Update Button.
C#
protected void OnCheckedChanged(object sender, EventArgs e)
{
bool isUpdateVisible = false;
CheckBox chk = (senderas CheckBox);
if (chk.ID == "chkAll")
{
foreach (GridViewRow row in gvCustomers.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked = chk.Checked;
}
}
}
CheckBox chkAll = (gvCustomers.HeaderRow.FindControl("chkAll") as CheckBox);
chkAll.Checked = true;
foreach (GridViewRow row in gvCustomers.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
for (int i = 1; i < row.Cells.Count; i++)
{
row.Cells[i].Controls.OfType<Label>().FirstOrDefault().Visible = !isChecked;
if (row.Cells[i].Controls.OfType<TextBox>().ToList().Count > 0)
{
row.Cells[i].Controls.OfType<TextBox>().FirstOrDefault().Visible = isChecked;
}
if (row.Cells[i].Controls.OfType<DropDownList>().ToList().Count > 0)
{
row.Cells[i].Controls.OfType<DropDownList>().FirstOrDefault().Visible = isChecked;
}
if (isChecked && !isUpdateVisible)
{
isUpdateVisible = true;
}
if (!isChecked)
{
chkAll.Checked = false;
}
}
}
}
btnUpdate.Visible = isUpdateVisible;
}
VB.Net
Protected Sub OnCheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim isUpdateVisible As Boolean = False
Dim chk As CheckBox = (TryCast(sender, CheckBox))
If chk.ID = "chkAll" Then
For Each row As GridViewRow In gvCustomers.Rows
If row.RowType = DataControlRowType.DataRow Then
row.Cells(0).Controls.OfType(Of CheckBox)().FirstOrDefault().Checked = chk.Checked
End If
Next
End If
Dim chkAll As CheckBox = (TryCast(gvCustomers.HeaderRow.FindControl("chkAll"), CheckBox))
chkAll.Checked = True
For Each row As GridViewRow In gvCustomers.Rows
If row.RowType = DataControlRowType.DataRow Then
Dim isChecked As Boolean = row.Cells(0).Controls.OfType(Of CheckBox)().FirstOrDefault().Checked
For i As Integer = 1 To row.Cells.Count - 1
row.Cells(i).Controls.OfType(Of Label)().FirstOrDefault().Visible = Not isChecked
If row.Cells(i).Controls.OfType(Of TextBox)().ToList().Count > 0 Then
row.Cells(i).Controls.OfType(Of TextBox)().FirstOrDefault().Visible = isChecked
End If
If row.Cells(i).Controls.OfType(Of DropDownList)().ToList().Count > 0 Then
row.Cells(i).Controls.OfType(Of DropDownList)().FirstOrDefault().Visible = isChecked
End If
If isChecked AndAlso Not isUpdateVisible Then
isUpdateVisible = True
End If
If Not isChecked Then
chkAll.Checked = False
End If
Next
End If
Next
btnUpdate.Visible = isUpdateVisible
End Sub
Updating the edited records in ASP.Net GridView Row
When Update Button is clicked, a FOR EACH loop is executed over the GridView rows.
Then, a check is performed if selected row is DataRow and again a check is performed if it is checked then, update query is executed and necessary parameters are set.
Finally, the Visible property of Update Button is set to FALSE and the BindGrid method is called.
C#
protected void OnUpdate(object sender, EventArgs e)
{
string sql = "UPDATE Customers SET Name = @Name, Country = @Country WHERE CustomerId = @CustomerId";
foreach (GridViewRow row in gvCustomers.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType <CheckBox>().FirstOrDefault().Checked;
if (isChecked)
{
SqlCommand cmd = new SqlCommand(sql);
cmd.Parameters.AddWithValue("@Name", row.Cells[1].Controls.OfType<TextBox>().FirstOrDefault().Text);
cmd.Parameters.AddWithValue("@Country", row.Cells[2].Controls.OfType<DropDownList>().FirstOrDefault().SelectedItem.Value);
cmd.Parameters.AddWithValue("@CustomerId", gvCustomers.DataKeys[row.RowIndex].Value);
this.ExecuteQuery(cmd, "SELECT");
}
}
}
btnUpdate.Visible = false;
this.BindGrid();
}
VB.Net
Protected Sub OnUpdate(ByVal sender As Object, ByVal e As EventArgs)
Dim sql As String = "UPDATE Customers SET Name = @Name, Country = @Country WHERE CustomerId = @CustomerId"
For Each row As GridViewRow In gvCustomers.Rows
If row.RowType = DataControlRowType.DataRow Then
Dim isChecked As Boolean = row.Cells(0).Controls.OfType(Of CheckBox)().FirstOrDefault().Checked
If isChecked Then
Dim cmd As SqlCommand = New SqlCommand(sql)
cmd.Parameters.AddWithValue("@Name", row.Cells(1).Controls.OfType(Of TextBox)().FirstOrDefault().Text)
cmd.Parameters.AddWithValue("@Country", row.Cells(2).Controls.OfType(Of DropDownList)().FirstOrDefault().SelectedItem.Value)
cmd.Parameters.AddWithValue("@CustomerId", gvCustomers.DataKeys(row.RowIndex).Value)
Me.ExecuteQuery(cmd,"SELECT")
End If
End If
Next
btnUpdate.Visible = False
Me.BindGrid()
End Sub
Screenshot
Demo
Downloads