This documentation is archived and is not being maintained.

Setting HTML Server Control Properties Programmatically

HTML server controls are of two slightly different types. The HTML elements most commonly used in forms are available as individual HTML server controls, such as HtmlInputText, HtmlInputButton, HtmlTable, and so on. These HTML server controls expose their own, control-specific properties that map directly to HTML attributes. However, any HTML element can be converted to a control. In that case, the element becomes an HtmlGenericControl with base class properties such as TagName, Visible, and InnerHTML.

To set properties of HTML server controls

  • Get or set the property name as you would with any object. All properties are either strings or integers. The following examples illustrate this:
    ' Visual Basic
    myAnchor.Href = "http://www.microsoft.com"
    Text1.MaxLength = 20
    Text1.Value = string.Format("{0:$###}", TotalCost)
    Span1.InnerHTML = "You must enter a value for Email Address."
    
    // C#
    myAnchor.HRef = "http://www.microsoft.com";
    Text1.MaxLength = 20;
    Text1.Value = string.Format("{0:$####}", TotalCost);
    Span1.InnerHtml = "You must enter a value for Email Address.";
    

All HTML server controls also support an Attributes collection, which gives you direct access to all the control's attributes. This is particularly useful for working with attributes that are not exposed as individual properties.

To work with control attributes directly

  • Use the properties and methods of a control's Attributes collection, such as Add, Remove, Clear, and Count. The Keys property returns a collection containing the names of all the attributes in the control. The following examples show various ways to use the Attributes collection:
    ' Visual Basic
    ' Adds new attribute.
    Text1.Attributes.Add("bgcolor", "red")
    ' Removes one attribute.
    Text1.Attributes.Remove("maxlength")
    ' Removes all attributes, clearing all properties.
    Text1.Attributes.Clear()
    ' Creates comma-delimited list of defined attributes
    Dim strTemp As String = ""
    Dim key As String
    For Each key In Text1.Attributes.Keys
       strTemp &= Text1.Attributes(key) & ", "
    Next
    
    // C#
    // Adds a new attribute.
    Text1.Attributes.Add("bgcolor","red");
    // Removes one attribute.
    Text1.Attributes.Remove("maxlength");
    // Removes all attributes, clearing all properties.
    Text1.Attributes.Clear();
    // Creates comma-delimited list of defined attributes
    string strTemp = "";
    foreach (string key in Text1.Attributes.Keys)
    {
       strTemp += Text1.Attributes[key] + ", ";
    }
    

See Also

Setting ASP.NET Server Control Properties | Setting Web Server Control Properties Programmatically

Show: