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
}
}
}

Multiple Lines in a Label Control

Recently when I was designing an ASP.Net form I came across a strange requirement where in static text had to be displayed in multiple lines. When I looked at it looked really simple.Just have as many Label controls as the number of lines.

But then I did not want to waste multiple controls.Well...err..I tried something silly and trivial and it served the purpose.

Lets say "This is the sample text I want to display in a Label on an ASP.Net form in a project" and I want this to be displayed in multiple lines.

The silly method goes like this.


Drag and drop a Label on to the ASP.net form.
Choose the Text property for the Label in the Designer.
This is the sample text <(br)>I want to display in a Label <(br)> on an ASP.Net form in a project.
Note: Remove the brackets ( and ) which will result in adding a line break to the text.


When the page renders the label will display the above text as below



This is the sample text
I want to display in a Label
on an ASP.Net form in a project.

Shift + Delete

One of the most useful shortcuts that I use frequently is the Shift + Delete to delete a line.Often as a programmer I found it really annoying to delete the lines using either Backspace or Delete iteself, sometimes just to clear out the commented code or to clear out the extra lines in a program.
Shift + Delete allows to delete a line,empty line and with the up,down arrow keys it can be used to delete multiple lines.
Another useful shortcut used to delete an entire word is Shift + Control + Delete in combination with the arrow keys.