Hi Waghmare,
Please refer below sample.
HTML
<asp:GridView ID="gvCustomers" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
AutoGenerateColumns="false" DataKeyNames="CustomerId">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkRow" runat="server" AutoPostBack="true" OnCheckedChanged="Checked" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CustomerId" HeaderText="CustomerId" ItemStyle-Width="150" />
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
Name:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnGetSelected" runat="server" Text="Update" OnClick="GetSelectedRecords" />
<br />
<asp:Label ID="lblCount" runat="server" />
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
Code
C#
int count = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, Name, Country FROM Customers", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
this.gvCustomers.DataSource = dt;
this.gvCustomers.DataBind();
}
}
}
protected void Checked(object sender, EventArgs e)
{
foreach (GridViewRow row in this.gvCustomers.Rows)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);
if (chkRow.Checked)
{
count++;
lblCount.Text = "Selected row : " + count.ToString();
}
}
}
protected void GetSelectedRecords(object sender, EventArgs e)
{
foreach (GridViewRow row in this.gvCustomers.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);
if (chkRow.Checked)
{
string id = row.Cells[1].Text;
string name = row.Cells[2].Text;
string country = (row.Cells[3].FindControl("lblCountry") as Label).Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
using (SqlCommand cmd = new SqlCommand("UPDATE Customers SET Name=@Name WHERE CustomerId=@CustomerId SELECT @@ROWCOUNT", con))
{
cmd.Parameters.AddWithValue("@CustomerId", id);
cmd.Parameters.AddWithValue("@Name", name + txtName.Text);
con.Open();
cmd.ExecuteNonQuery();
count++;
con.Close();
}
}
}
}
lblCount.Text = "Selected rows updated : " + count.ToString();
}