Updating DataTable bound to ASP.Net DataGrid
I am having a problem updating a datatable that is bound to a datagrid. Tried a bunch of approac开发者_如何学JAVAhes but the problem is the underlying datatable reverts back to its initial state everytime u click a command.
Here's the example code:
On Label Click:
protected void OnUserDataGridCommand(object source, DataGridCommandEventArgs e)
{
DataTable dt = DataGridUsers.DataSource as DataTable;
if (e.CommandName == "Lock Out")
{
// Approach 1
e.Item.Cells[0].Text = "Lock";
DataGridUsers.DataSource = dt;
DataGridUsers.DataBind();
// Approach 2
dt.Rows[e.Item.ItemIndex]["FirstName"] = "LOCK";
dt.Rows[e.Item.ItemIndex].AcceptChanges();
DataGridUsers.DataSource = dt;
DataGridUsers.DataBind();
}
}
So this will update the row's first name to say Lock but when you click on another row the previously Locked will revert to the first name. When I breakpoint regardless of a row displaying lock, the datatable always is the initial data (no "LOCK" data).
This line typically doesn't work for me
DataTable dt = DataGridUsers.DataSource as DataTable;
You might want to instead manage the DataSource in the session, by retrieving it out of session doing your modifications and then rebind it to the Grid.
You might also want to take a look at where the DataSource got bound to the grid the first time. Is is it running on the postback thus overwriting your changes.
精彩评论