HtmlTextWriter::AddStyleAttribute Method (HtmlTextWriterStyle, String^)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

Adds the markup style attribute associated with the specified HtmlTextWriterStyle value and the attribute value to the opening markup tag created by a subsequent call to the RenderBeginTag method.

Namespace:   System.Web.UI
Assembly:  System.Web (in System.Web.dll)

virtual void AddStyleAttribute(
	HtmlTextWriterStyle key,
	String^ value


Type: System.Web.UI::HtmlTextWriterStyle

An HtmlTextWriterStyle that represents the style attribute to add to the output stream.

Type: System::String^

A string that contains the value to assign to the attribute.

Use the AddStyleAttribute overload of the AddStyleAttribute(HtmlTextWriterStyle, String^) method when the style is a member of the HtmlTextWriterStyle enumeration and is known before run time.

The HtmlTextWriter class maintains a list of styles for the markup elements it renders. When the RenderBeginTag method is called, any styles added by the AddStyleAttribute method are rendered to the opening tag of the element. The list of styles is then cleared.

The coding pattern for rendering markup elements is as follows:

  • Use the AddStyleAttribute method to add any style attributes to the element.

  • Use the RenderBeginTag method.

  • Use other methods as needed to render the content found between the element opening and closing tags.

  • Use the RenderEndTag method.

The following code example demonstrates how to use part of an override of the RenderBeginTag method in a class derived from the HtmlTextWriter class. The code checks whether a <Label> element is being rendered. If so, the IsStyleAttributeDefined method is called to check whether a Color style attribute has been defined for the <Label> element. If a Color attribute has not been defined, the code calls this overload of the AddStyleAttribute method to add the Color attribute to the style attribute, and then set its value to red.

// If the markup element being rendered is a Label,
// render the opening tag of a <Font> element before it.
if ( tagKey == HtmlTextWriterTag::Label )

   // Check whether a Color style attribute is
   // included on the Label. If not, use the
   // AddStyleAttribute and GetStyleName methods to add one
   // and set its value to red.
   if (  !IsStyleAttributeDefined( HtmlTextWriterStyle::Color ) )
      AddStyleAttribute( GetStyleName( HtmlTextWriterStyle::Color ), "red" );

.NET Framework
Available since 1.1
Return to top