Everyone who has interviewed for a .NET programming position has had to answer some question about the order of events during an ASP.NET page's life-cycle. Having an answer for an interviewer is not enough. You really need to know the order of events down to the minutae in order to avoid wasting valuable time during development.
Case in point: my most recent attempt to implement a GridView control in the EditItemTemplate of a FormView. The FormView is used for editing groups of people. The basic form captures aggregate information about the group, but, of course, it has a list of people as well.
I like the FormView. Nothing is more tedious than laying out TextBoxes and Labels, but hook a FormView up to a DataSource, et voila, instant form. Feels like the 90s all over again, working in MS Access. However, you rarely can get paid for the easy stuff. In this case, I needed to add a GridView to the EditItemTemplate to manage the list of people in my group. When I first dragged one in and hooked it up to a SqlDataSource, I didn't see any data when I clicked "Edit". OK...no problem. Obviously, the GridView needed to be told to Bind to the data.
So, I added this event:
protected void frmvGroups_ModeChanged(object sender, EventArgs e)
{
if (frmvGroups.CurrentMode == FormViewMode.Edit)
{
GridView pGrid = (GridView)frmvGroups.FindControl("gvwParticipants");
pGrid.DataBind();
}
}
WRONG ANSWER!
I got a null reference to the GridView. It took me a while to figure out why. If I had thought "order of events" right at the start, it would have been a no-brainer, but that thought eluded me long enough to warrant writing this post in case I neglect "order of events" in the near or distant future.
The problem, of course, is that the GridView has not yet been brought into existence at the moment the FormView has finished changing its mode from ReadOnly to Edit. It changes its mode then starts to render the controls in the template. So, when is it safe to reference the GridView? The DataBound event is probably the most logical place.
THIS WORKS:
protected void frmvGroups_DataBound(object sender, EventArgs e)
{
if (frmvGroups.CurrentMode == FormViewMode.Edit)
{
GridView pGrid = (GridView)frmvGroups.FindControl("gvwParticipants");
pGrid.DataBind();
}
}