How to: Set 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 example illustrates setting property names:

    Dim TotalCost As Integer
    myAnchor.HRef = "https://www.microsoft.com"
    Text1.MaxLength = 20
    Text1.Text = String.Format("{0:$###}", TotalCost)
    Span1.InnerHtml = "You must enter a value for Email Address."
    
    myAnchor.HRef = "https://www.microsoft.com";
    Text1.MaxLength = 20;
    Text1.Text = string.Format("{0:$####}", TotalCost);
    Span1.InnerHtml = "You must enter a value for Email Address.";
    

Setting Attributes

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:

        ' 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
    End Sub
    
    // 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

Tasks

How to: Set ASP.NET Server Control Properties

Other Resources

Setting ASP.NET Server Control Properties Programmatically