如何:通过编程方式设置 HTML 服务器控件的属性

更新:2007 年 11 月

HTML 服务器控件有两个略有差异的类型。窗体中最常用的 HTML 元素可用作单独的 HTML 服务器控件,例如 HtmlInputTextHtmlInputButtonHtmlTable 等等。这些 HTML 服务器控件公开其自身和控件有关的属性,这些属性直接映射为属性。但是,任何 HTML 元素都可以转换为控件。在这种情况下,元素变为 HtmlGenericControl,且具有 TagName、Visible 和 InnerHTML 等基类属性。

设置 HTML 服务器控件的属性

  • 向对任何对象一样获取或设置属性名。所有属性或者是字符串或者是整数。

    下面的示例阐释如何设置属性名称:

    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.";
    

设置属性

所有 HTML 服务器控件还支持 Attributes 集合,该集合为您提供对所有控件属性的直接访问。对于使用没有公开为单独属性的特性而言尤为有用。

直接使用控件属性

  • 使用控件的 Attributes 集合的属性和方法,如 Add、Remove、Clear 和 Count。Keys 属性返回包含控件中所有属性的名称的集合。下面的示例演示使用 Attributes 集合的各种方法:

        ' 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] + ", ";
    }
    

请参见

任务

如何:设置 ASP.NET 服务器控件属性

其他资源

以编程方式设置 ASP.NET 服务器控件属性