The FormView control and its small “traps”

It was long time that don’t get into an ASP.Net project, and since I was standing at ASP.Net 1.1, this was the best occasion to wipe out the old conoissance and start with the new control released with ASP.Net 2.0

Between the new controls shipped with the "new" framework there is the FormView, an interesting control. As usual in Microsoft did a great job, but as usual too they forget to leave clean and easy the obviously things.

For people used to the old approach, accessing at page’s controls means to declare a protected internal HtmlGenericControl inside the code behind file (if the control was a stanrdard HTML control surrounded with the attribute runat="server") or a variable of the same type of the object dragged into the page.

Within the FormView this kind of approach doesn’t work at all. The FormView act as a sort of closed box inaccessible from the code-behind file. At least, on a first look it was what I though.

Also using the FindControl method doesn’t let me the expected results.

So, after some researches, I finally understood that inside the page’s OnLoad method, the FormView has not been initialized; the control contained inside the FormView doesn’t exist in the page scope yet. To get access them is necesary wait that all controls will created and then simple access to them using the ItemCreated event of the object.

Example:

protected void FormView1_ItemCreated(object sender, EventArgs e)
{
  Panel myPanel = (Panel)FormView1.FindControl("myPanel");
  if (true)
    myPanel.Visible = false;
  else
    ......
}

Another thing that let me lost some time was to try get access at the DataSource binded to the FormView. Also here, after some research, the code necessary to do this is:

Example:

protected void FormView1_DataBound(object sender, EventArgs e)
{   
   DataRowView r = (DataRowView)FormView1.DataItem;
   ....
}

In this way the DataRowView object will capture the content of the binded DataSource and, through the Row property accessible within its index, it will be possible to retrieve the single item of the returned data.