Just simply put the binding code out side of IsNotPostback. Here i have also used OnRowDeleting Event.
Refer this example.
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
runat="server" AutoGenerateColumns="false" OnRowDeleting="GridView1_RowDeleting" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" />
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
</div>
</form>
C#:
protected void Page_Load(object sender, EventArgs e)
{
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();
ViewState["Table"] = dt;
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int rowIndex = e.RowIndex;
DataTable dt = (DataTable)ViewState["Table"];
dt.Rows.RemoveAt(rowIndex);
GridView1.DataSource = dt;
GridView1.DataBind();
ViewState["Table"] = dt;
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TableCell cell = new TableCell();
ImageButton bttn = new ImageButton();
bttn.CommandName = "Delete";
bttn.CommandArgument = e.Row.Cells[0].Text;
bttn.ImageUrl = "delete.png";
bttn.ToolTip = "Click to delete this record";
bttn.Click += new ImageClickEventHandler(btnTest_Click);
cell.Controls.Add(bttn);
e.Row.Cells.Add(cell);
bttn.OnClientClick = "return confirm('Are you sure you to delete " + e.Row.Cells[0].Text + "?');";
}
}
protected void btnTest_Click(object sender, EventArgs e)
{
}
Thank You.