Click here to download the sample source code for this lesson.
In the previous lesson Intro to ASP.NET server controls, we covered how to change the appearance of server controls such as Buttons, TextBoxes and DropDownLists by using the Properties window. There are situations where you need to change the appearance or behavior of server controls dynamically at runtime; this is accomplished by using C# in the code behind .cs file. You can do a number of different things using code such as hiding controls, changing their color, changing their font, and even setting focus of the cursor to a particular control.
Let’s do an example. Create a new web form named Default2.aspx and go to the Design view. Drag a Button onto the web form. Drag a TextBox next to the Button. Drag a DropDownList next to the TextBox. Finally, drag a Label next to the DropDownList. Double click the Button to create a new event handler method and put:
DropDownList1.Visible = false; Label1.ForeColor = System.Drawing.Color.Red; Label1.Font.Size = FontUnit.XSmall; TextBox1.Focus();
Click play to run the application and click on the Button once the web page comes up. Notice that the DropDownList disappears, the Label’s size and color changes and the cursor gets placed inside the TextBox control.