Tutorials » AspNet tutorials »

Changing properties dynamically at run time

This article explains how to change the properties of web controls at run time.

In the previous chapter, you learnt 2 ways to change the properties of a web control:

1. Change in the Properties window in design mode
2. Type the properties manually in aspx page in HTML mode.

These two methods allows you to set the properties at the time of designing the page. What if you need to change the properties at run time?

You may have one label control in the page which you use to display the success or error message depending some conditions. For example, in a "Login" page, if the login id or password is wrong, you want to display the error message in Red color. If the login information is correct, you want to display a welcome message in Green color. For the both the messages you can use same Label control. Only thing is, you need to change the Font color at run time depending on the login status.

To try this out, let us create a sample web page and drag & drop a Label control to it. (You can use the default web page created in the previous chapters.)

In the Page_Load event, write the following code:

Label1.Forecolor = Color.FromName("GREEN")
Label1.Text = "Successfully processed."

Run the page. You will see your message in green color.

Now change the code as shown below:

Label1.Forecolor = Color.FromName("Red")
Label1.Text = "An error occurred."

If you run the page now, it will show your message in red color.

In the above example, "Color" is a class part of .NET Framework and "FromName()" is a method of this class.

Using the above approach, you can change any of the properties of the web controls at run time. In addition to changing the properties, you can retrieve the values also from the web controls using the same approach. For example, if you have a Textbox control in the web page, you can get the value typed by user using the above approach.

You will learn more about Textbox control and its properties in the coming chapters.

Next Chapter: TextBox and Button controls in ASP.NET
Previous Chapter: Introduction to ASP.NET Web Controls
More Chapters: ASP.NET Tutorials
More Tutorials: Tutorial Index

Top Contributors
    Last 7 Daysmore...

    Awards & Gifts

    Online Members

    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India