DataGrid Edit Column Does Nothing
I had to kick myself since I knew I had experienced this same issue before and since it's such a novice issue, but I couldn't remember how to fix it! It finally dawned on me (it was really a stupid thing) so I figured I'd post about it for anyone else out there kicking themselves for being stuck on the same problem.
In the subroutine you have your DataGrid's EditCommand event bound to, you need to set the grid's EditItemIndex to e.Item.ItemIndex, and rebind the contol! Example:
private void Page_Load(object sender, System.EventArgs e)
{
dgDealers.EditCommand += new DataGridCommandEventHandler(dgDealers_EditCommand);
if(!this.IsPostBack)
{
LoadGridData();
}
}
private void LoadGridData()
{
// Get the data from the database.
SqlConnection conn = db.NewOpenConn();
SqlDataAdapter da = new SqlDataAdapter("EXECUTE SelectDealers",conn);
DataTable dt = new DataTable("dealers");
//Fill it into the DataGrid.
da.Fill(dt);
dgDealers.DataSource = dt;
dgDealers.DataBind();
ViewState["gridData"] = dt;
//Cleanup.
conn.Close();
da.Dispose();
conn.Dispose();
}
private void RebindGrid()
{
//Set the DataSource to the DataTable previously saved in the ViewState
dgDealers.DataSource = ViewState["gridData"];
dgDealers.DataBind();
}
private void dgDealers_EditCommand(object source, DataGridCommandEventArgs e)
{
dgDealers.EditItemIndex = e.Item.ItemIndex;
RebindGrid();
}
In my example, when I make my call to the Database I store the resulting DataTable in the ViewState. Later, in the EditCommand event for my grid (highlighted) I set the grid's EditItemIndex to e.Item.ItemIndex and call a function (RebindGrid) that re-retrieves the grid's data from the ViewState and re-executes DataBind on the DataGrid.
Now, you may want to instead cache your data in a Session variable, Caching object, or not at all (and retrieve the data again from your original DataSource) - depending on your data and how much you have. Also, as far as I know, this is the same whether you're using the either .NET Framework 1.1 or 2.0. You also need to make sure EnableViewState is set to true for your DataGrid.
If anyone knows a better way to do this (without having to rebind the DataSource), please let us all know in the comments. It's ridiculous that you need to do such a thing, especially since the data is essentially already being stored in your ViewState for the DataGrid.
Labels: Coding



0 Comments:
Post a Comment
Links to this post:
Create a Link
<< Blog Home