Random programming things I'd want to remember

Monday, May 11, 2009

How to edit a GridView items inside a repeater?

You know, the usual:

<asp:Repeater ...
<itemtemplate>
<asp:gridview id="gv1" runat="server">
</itemtemplate>
</asp:Repeater>

When I was working on my app, I had a long gridview of multiple records per day, multiple days, all one list. When it was 10 records, it was ok. But as I started adding data, it started looking long and boring. I decided to group it by day, and it looked nice until I had to edit individual records. I did not change any event declarations from before, my methods had the same names, and they seem to be working, but none of the gridviews would change their edititemindexes. I checked out a couple of posts and people had the same issues, they assign events, they get executed, but gridviews would not react in any way.

The problem is happening because every time I'd call .DataBind method on the Repeater (then calling the .DataBind method on individual gridviews in the repeater's ItemDataBound event), the entire Repeater would get rebuilt and the EditItemIndex property on that particular gridview would not matter anymore because the server would not know which gridview needed to be edited.

The trick was relatively easy. Instead of rebinding the entire repeater, only that particular gridview needed to be re-databound. I figured out a way to pull just those particular day's records and my GridView_RowEditing event looks like:

protected void GridView1_RowEditing(object sender, GridViewEventArgs e)
{
GridView gv1 = (GridView)sender;
if(gv1 != null)
{
gv1.EditIndex = e.NewEditIndex;
gv1.DataSource = myDataSource;
gv1.DataBind();
}
}

Instead of binding the entire Repeater and losing all valuable information, I just bound that particular gridview by casting the sender object as a GridView. RowCancelingEvent and RowUpdatingEvent -- same thing. Cast the sender object and work with it as much as you need.