Wednesday, September 5, 2007

Accessing Formview controls Dynamically ASP.Net code behind file

Ever tried to access the formview controls programmatically?Well I did and had to spend quite sometime to figure out because I am no expert in ASP.net.
The requirement was to loop or iterate through all the controls on the page and set some of the properties of the controls dynamically.Since I wanted to do this before I could tie or bind the data in Page_Load I put the code in Page_Init. To add to my woes the technology chosen for the middle tier does not allow me to step through and I have been using logging tool send the values and manually check.
foreach(Control ctrl in this.Page.Controls)
{
//Do something
}
The above code does not work for formview because the formview controls are not instanstiated till data is bound to it unless the default mode is insert mode.So in order to access the formview controls loop through formview controls after the data is bound to the controls i.e after Page_Load.Page_PreRender is a better option compared to Page_Init.

protected void Page_PreRender(object sender,EventArgs e)
{
foreach(Control ctrl in this.Page.Controls)
{
if(ctrl.GetType().ToString() == "FormView")
foreach(Control fctrl in ctrl.Controls)
{
//Do Something
}
}
}

No comments: