Topic: Datagrid - Deleting a row
Share/Save/Bookmark
C# DATAGRID Deleting a row
 
1. Create a connection, data adapter, dataset, and a datagrid like you would normally do
 
2. Mirror the code below for the Page_Load event
      if (!IsPostBack)
      {
            da_MyDataAdapter.Fill(ds_MyDataSet1);
            Session["ds_MyDataSet"] = ds_MyDataSet1;
      }
      else
      {
            ds_MyDataSet1 = (ds_MyDataSet)Session["ds_MyDataSet"];
      }
      grd_MyGrid.DataBind();
     
3. Mirror the code below for the ItemCommand for the datagrid.
    NOTE: This only deletes the row from the dataset, not the database
        // If the Delete Button was clicked
      if (e.CommandName == "Delete")
      {
            // Put the GUID value into a guid variable
            System.Guid MyGUID = new System.Guid(grd_MyGrid.Items[e.Item.ItemIndex].Cells[0].Text);
            // Define a Row variable
            ds_MyDataSet.RowInDataSet rowDelete;
            // Set the row to the row determined by the MyGUID
            rowDelete = ds_MyDataSet1. RowInDataSet.FindByPlayerGUID(MyGUID);
            // Delete the row
            rowDelete.Delete();
            // Re-bind the grid
            grd_MyGrid.DataBind();
      }
 
4. The following event procedures for the Restore and Commit buttons let the user restore the data set to its previous
    state or, alternatively, update the database with the deletions made in the preceding code:
      private void btn_Restore_Click(object sender, System.EventArgs e)
      {
            // Restore the data set to its original state
            ds_MyDataSet1.RejectChanges();
            // Refresh the datagrid
            grd_MyGrid.DataBind();
      }
 
      private void btn_Commit_Click(object sender, System.EventArgs e)
      {
            int int_Rows;
            // Update the database from the dataset
            int_Rows = da_MyDataAdapter.Update(ds_MyDataSet1);
            // Save the changes to state variable
            Session["ds_MyDataSet"] = ds_MyDataSet1;
            // Refresh the datagrid
            grd_MyGrid.DataBind();
      }