News & UpdatesProgrammingWeb programming Store My Projects
Links
Affiliates

ASP.NET Tutorial – 06 – Control Members

This section will cover some of the generic members of the HTML controls. Because all HTML controls inherit from the Control class, most of their members are the same. The only differences between the controls are the properties relating to the corresponding elements’ specific attributes. Therefore, the members covered in this section exist for all HTML controls. For illustration, a generic control will be used.

HtmlGenericControl gen = new HtmlGenericControl("div");
myForm.Controls.Add(gen);

Generic Properties

The first useful property to know about is InnerText, which adds text that will be displayed inside of the element.

gen.InnerText = "Hello World";

A similar field is InnerHtml. This field adds HTML inside of the element, instead of just text. Keep in mind that these two fields will override each other.

gen.InnerHtml = "Hello<br />HTML";

Another valuable property is Visible, which can be set to false to hide an element.

gen.Visible = false;

Generic Collections

The HTML controls share a couple of important collections. First, the “Attributes” collection can change the attributes of a control.

gen.Attributes.Add("align", "center");

Similarly, the “Style” collection can change the CSS style of a control.

gen.Style.Add(HtmlTextWriterStyle.FontWeight, "bold");

Finally, the “Controls” collection is used to change the controls contained within the referencing control. Note that since HTML pages are organized as a tree it’s possible to navigate through the child controls using this collection. For example, to get the first child element of the form control you would reference the first element in the collection (as if it was an array).

Control c = myForm.Controls[0];

The Parent property can be used to get the parent of the control.

c = gen.Parent; // get myForm
Recommended additional reading:
Sams - Teach Yourself ASP.NET 3.5 in 24 Hours