' Visual Basic Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load If Me.IsPostBack Then DsBooks1 = CType(Session("DsBooks"), dsBooks) Else Me.SqlDataAdapter1.Fill(Me.DsBooks1) Session("DsBooks") = DsBooks1 DataGrid1.DataBind() End If End Sub
// C# private void Page_Load(object sender, System.EventArgs e) { if(this.IsPostBack) { dsBooks1 = (dsBooks) Session["DsBooks"]; } else { this.sqlDataAdapter1.Fill(this.dsBooks1); Session["DsBooks"] = dsBooks1; this.DataGrid1.DataBind(); } } For information about maintaining state, see Web Forms State Management in the Visual Studio documentation.
You can update the record normally. For an example, see Walkthrough: Using a DataGrid Web Control to Read and Write Data in the Visual Studio documentation. After updating the dataset, update the database, then refresh the dataset. Be sure to save the refreshed dataset to Session state again. Here is an example of an update handler:
' Visual Basic Private Sub DataGrid1_UpdateCommand(ByVal source As Object, _ ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) _ Handles DataGrid1.UpdateCommand Dim dr As Dataset.BooksRow 'Get a reference to row zero (where the row was inserted) dr = Me.DsBooks1.Books(0) Dim tb As TextBox = CType(e.Item.Cells(2).Controls(0), TextBox) dr.title = tb.Text Dim cb As CheckBox = CType(e.Item.Cells(3).Controls(1), CheckBox) dr.instock = cb.Checked Me.SqlDataAdapter1.Update(Me.DsBooks1) DataGrid1.EditItemIndex = -1 'Refresh the dataset from the database DsBooks1.Clear() Me.SqlDataAdapter1.Fill(Me.DsBooks1) 'Save the refreshed dataset in Session state agin Session("DsBooks") = DsBooks1 DataGrid1.DataBind() End Sub
// C# private void DataGrid1_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { dsBooks.BooksRow dr; //Get a reference to row zero (where the row was inserted) dr = this.dsBooks1.Books[0]; TextBox tb1 = (TextBox) e.Item.Cells[2].Controls[0]; dr.title = tb1.Text; CheckBox cb = (CheckBox) e.Item.Cells[3].Controls[1]; dr.instock = cb.Checked; this.sqlDataAdapter1.Update(this.dsBooks1); DataGrid1.EditItemIndex = -1; //Refresh the dataset from the database dsBooks1.Clear(); this.sqlDataAdapter1.Fill(this.dsBooks1);