I've been getting away from DataGrids more and more lately, but there's still no substitute for an editable DataGrid for administrative pages:
<asp:DataGrid Runat=server ID=grdSeries DataKeyField="series_id" AutoGenerateColumns=False CellPadding=2 CellSpacing=2 BorderWidth=0>
<Columns>
<asp:EditCommandColumn EditText="Edit Series" CancelText="Cancel" UpdateText="OK"></asp:EditCommandColumn>
<asp:TemplateColumn HeaderText="Series Name" >
<ItemTemplate>
<asp:Label Runat=server Text='<%# DataBinder.Eval(Container.DataItem, "series_name") %>' ID="Label1"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditName" Runat=server Text='<%# DataBinder.Eval(Container.DataItem, "series_name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Description" >
<ItemTemplate>
<asp:Label Runat=server Text='<%# DataBinder.Eval(Container.DataItem, "description") %>' ID="Label2"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID=txtEditDescription Runat=server Text='<%# DataBinder.Eval(Container.DataItem, "description") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
Now for the events in the code behind that run this:
private void grdSeries_Cancel(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
grdSeries.EditItemIndex = -1;
SubmitSearch();
}
private void grdSeries_Edit(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
grdSeries.EditItemIndex = Convert.ToInt32(e.Item.ItemIndex);
SubmitSearch();
}
private void grdSeries_Update(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
Series objSeries = new Series();
objSeries.SeriesName = ((TextBox)e.Item.FindControl("txtEditName")).Text;
objSeries.SeriesDescription = ((TextBox)e.Item.FindControl("txtEditDescription")).Text;
objSeries.SeriesID = Convert.ToInt32(grdSeries.DataKeys[e.Item.ItemIndex]);
if (!objSeries.Save())
{
lblMessage.Text = "There was an error updating your series changes.";
}
grdSeries.EditItemIndex = -1;
SubmitSearch();
}
where SubmitSearch() just does the search and repopulates the grid. The trick to getting this to work is pulling the data from the controls from the editable row out of the DataGridCommandEventArgs parameter using “FindControl” and casting it to the correct type. Also note the use of the DataKeyField to relate each row with a primary key in a database.
Hopefully this sparks some ideas with someone out there. I know that when I was “coming through the ranks” of ASP.NET, when I realized I could make a DataGrid that was editable in place that was the moment that I realized that you could do some REALLY cool things with ASP.NET.