Hi akhter,
I have created a sample please take its reference and correct your code.
HTML
<asp:GridView runat="server" ID="gvCustomers" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView><br /><br />
<asp:Button Text="Delete All Row" runat="server" ID="btnDelete" OnClick="DeleteGridviewRow" />
Namespaces
C#
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
VB.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindCustomer();
}
}
private void BindCustomer()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT CustomerID,Name,Country FROM Customers", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter())
{
sda.SelectCommand = cmd;
DataTable dt = new DataTable();
sda.Fill(dt);
this.gvCustomers.DataSource = dt;
this.gvCustomers.DataBind();
}
}
}
}
protected void DeleteGridviewRow(object sender, EventArgs e)
{
foreach (GridViewRow row in gvCustomers.Rows)
{
int id = Convert.ToInt32(row.Cells[0].Text);
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("DELETE FROM Customers WHERE CustomerId=@CustomerId", con))
{
cmd.Parameters.AddWithValue("@CustomerId", id);
cmd.CommandType = CommandType.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindCustomer()
End If
End Sub
Private Sub BindCustomer()
Using con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("conString").ConnectionString)
Using cmd As SqlCommand = New SqlCommand("SELECT CustomerID,Name,Country FROM Customers", con)
cmd.CommandType = CommandType.Text
Using sda As SqlDataAdapter = New SqlDataAdapter()
sda.SelectCommand = cmd
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
Me.gvCustomers.DataSource = dt
Me.gvCustomers.DataBind()
End Using
End Using
End Using
End Sub
Protected Sub DeleteGridviewRow(ByVal sender As Object, ByVal e As EventArgs)
For Each row As GridViewRow In gvCustomers.Rows
Dim id As Integer = Convert.ToInt32(row.Cells(0).Text)
Using con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("conString").ConnectionString)
Using cmd As SqlCommand = New SqlCommand("DELETE FROM Customers WHERE CustomerId=@CustomerId", con)
cmd.Parameters.AddWithValue("@CustomerId", id)
cmd.CommandType = CommandType.Text
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
Next
End Sub