How do you delete data from a DataGrid?

  • Thread starter Thread starter Mark Jones
  • Start date Start date
M

Mark Jones

I'm trying to delete data from a DataGrid using a ButtonColumn with a
CommandName="Delete" but it's not working a the min. I'm using session data
which fills a DataTable which then fills the DataGrid. The code is as
follows (dgBasket is the DataGrid):

private void Page_Load(object sender, System.EventArgs e)

{

DataTable myTable = (DataTable) Session["Basket"];

dgBasket.DataSource = myTable;

dgBasket.DataKeyField = "Product";

dgBasket.DataBind();

}


private void dgBasket_DeleteCommand(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs e)

{

int rowToDelete = e.Item.ItemIndex;


DataTable myTable = (DataTable) Session["Basket"];

DataRowCollection myRows = myTable.Rows;

DataRow thisRow = myTable.Rows.Find(rowToDelete);

thisRow.Delete();

Session["Basket"] = myTable;

dgBasket.DataSource = myTable;

dgBasket.EditItemIndex = -1;

dgBasket.DataKeyField = "Product";

dgBasket.DataBind();

}



When I press one of the delete buttons nothing happens - the page reloads
but no info is deleted. Does anyone know where I'm going wrong?

Mark Jones
 
Try not to databind the controls each time, only first time

if ( ! IsPostBack ) {
DataTable myTable = (DataTable) Session["Basket"];

dgBasket.DataSource = myTable;

dgBasket.DataKeyField = "Product";

dgBasket.DataBind();
}

in Page_Load

Hope this helps.

Dan Cimpoiesu
 
Dan,

I added the code you suggested but to no avail. Any other ideas?

Mark Jones


Dan Cimpoiesu said:
Try not to databind the controls each time, only first time

if ( ! IsPostBack ) {
DataTable myTable = (DataTable) Session["Basket"];

dgBasket.DataSource = myTable;

dgBasket.DataKeyField = "Product";

dgBasket.DataBind();
}

in Page_Load

Hope this helps.

Dan Cimpoiesu

Mark Jones said:
I'm trying to delete data from a DataGrid using a ButtonColumn with a
CommandName="Delete" but it's not working a the min. I'm using session data
which fills a DataTable which then fills the DataGrid. The code is as
follows (dgBasket is the DataGrid):

private void Page_Load(object sender, System.EventArgs e)

{

DataTable myTable = (DataTable) Session["Basket"];

dgBasket.DataSource = myTable;

dgBasket.DataKeyField = "Product";

dgBasket.DataBind();

}


private void dgBasket_DeleteCommand(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs e)

{

int rowToDelete = e.Item.ItemIndex;


DataTable myTable = (DataTable) Session["Basket"];

DataRowCollection myRows = myTable.Rows;

DataRow thisRow = myTable.Rows.Find(rowToDelete);

thisRow.Delete();

Session["Basket"] = myTable;

dgBasket.DataSource = myTable;

dgBasket.EditItemIndex = -1;

dgBasket.DataKeyField = "Product";

dgBasket.DataBind();

}



When I press one of the delete buttons nothing happens - the page reloads
but no info is deleted. Does anyone know where I'm going wrong?

Mark Jones
 
Back
Top