asp.netdatatablepaginationinsertrow

ASP.net inserted row in Datatable disappearing on page change


So I have a datatable on my website and it displayed 10-20 rows of filled data. I have added a line of code that inserts a empty row in the existing datatable with the below code:

 dt.Rows.InsertAt(datatable.NewRow, 8)

I also have this which is required for doing paging in the datatable:

 Protected Sub GridView3_PageIndexChanging(sender As Object, e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView3.PageIndexChanging
    GridView3.PageIndex = e.NewPageIndex
    GridView3.DataBind()
End Sub

The problem is when I move from page 1 to 2 then back to 1, all the inserted rows disappear leaving only the filled rows. Is there a way to keep the inserted rows?? Or does anyone have any explanation or solution for this?

Thanks.


Solution

  • Your call to DataBind is rebuilding the GridView from its original data. You will need to make sure the data set you are binding to includes the added items. Typically, I have a method that gathers the items from the page and binds using those items.

    In your case, you will just want to re-bind against the DataTable (named dt in your example code) when you add a new row.

    GridView3.DataSource = dt
    

    This means that you will have to keep it around somewhere. It is unclear from your code where the original DataTable comes from, so I don't really have any suggestions on where you might proceed next. And since your grid supports paging, my typical approach doesn't even work.

    Simply put, because this is a web page, the server remembers nothing between postbacks that isn't persisted somewhere. Your options are to save it into the page somewhere, to save it to a database somewhere, or to save it to the session - a really bad idea for data sets of any significant size.

    If you are going to be persisting the data eventually, you might be able to piggyback that persistence now - save it after the add and whenever edits are completed, the re-bind against the persisted data.