Dorababu Meka

Dorababu Meka

  • 213
  • 8.3k
  • 1.7m

Dynamically removing rows from a grid view

Jun 2 2011 11:40 AM
I am writing code to dynamically add rows to grid view by clicking on the buttons available. The ADD button will add new rows to grid view and the Delete button will delete a row.

I would like to restrict deletion to new rows that were inserted but as by the Add button. Currently, the code allows users to delete the first record populating the grid view and I would like to prevent this.

Can any one give me an idea?

First form which was initially loaded: I am adding text to text box and later I will click on Add



Second form which will be loaded after clicking ADD:



If I click Delete on the red highlighted field, I don't want to delete it, as it is my first record. In this case, I would like delete to remove the later record.

Here is my code:

protected void btndelete_click(object sender, EventArgs e)
   
{
       
Button lb = (Button)sender;
       
GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
       
int rowID = gvRow.RowIndex + 1;
       
if (ViewState["CurrentTable"] != null)
       
{
           
DataTable dt = (DataTable)ViewState["CurrentTable"];
           
if (dt.Rows.Count > 1)
           
{
               
if (gvRow.RowIndex < dt.Rows.Count - 1)
               
{
                   
//Remove the Selected Row data
                    dt
.Rows.Remove(dt.Rows[rowID]);
               
}
           
}
           
//Store the current data in ViewState for future reference
           
ViewState["CurrentTable"] = dt;
           
//Re bind the GridView for the updated data
           
GridView1.DataSource = dt;
           
GridView1.DataBind();
       
}

   
}

Any help is appreciated.



Answers (4)