In my previous post, I have posted the updated the codes about Adding Dynamic Rows in ASP.Net GridView Control with TextBoxes because there is a bug on that. So obviously the codes in my other example about Adding a Delete functionality in Dynamic TextBoxes in GridView is affected. To fix the issue then you can refer to this updated code below:

 

    protected void LinkButton1_Click(object sender, EventArgs e)

    {

        LinkButton lb = (LinkButton)sender;

        GridViewRow gvRow = (GridViewRow) lb.NamingContainer;

        int rowID = gvRow.RowIndex;

        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]);

                  ResetRowID(dt);

              }

          }

            //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();

        }

 

        //Set Previous Data on Postbacks

        SetPreviousData();

    }

 

    private void ResetRowID(DataTable dt)

    {

        int rowNumber = 1;

        if (dt.Rows.Count > 0)

        {

            foreach (DataRow row in dt.Rows)

            {

                row[0] = rowNumber;

                rowNumber++;

            }

        }

    }

 

If you notice, I have added the method ResetRowID() so that the row number will be sequenced when deleting a row in the Grid.

 

That’s it! Happy coding!

Technorati Tags: ,,