If you have set the dataKeyNames in the GridView And you have set the BoundField column to visible false the you need to find the DataKey value of each row to delete.
foreach (GridViewRow row in this.GridView1.Rows)
{
int id = Convert.ToInt32(this.GridView1.DataKeys[row.RowIndex].Value);
}
Complete Example
HTML
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" DataKeyNames="Id" HeaderStyle-ForeColor="White"
runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" Visible="false" />
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
<asp:Button Text="Delete All Rows" OnClick="DeleteAll" runat="server" />
Namespace
using System.Data;
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Country",typeof(string)) });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
// You need to write the Delete code inside foreach loop
protected void DeleteAll(object sender, EventArgs e)
{
foreach (GridViewRow row in this.GridView1.Rows)
{
int id = Convert.ToInt32(this.GridView1.DataKeys[row.RowIndex].Value);
}
}