次の方法で共有


How to: Set ASP.NET Server Control Style Properties Programmatically

You can set style properties of an ASP.NET server control programmatically, which allows you to change the appearance of a control conditionally.

To set style properties programmatically

  • Use the following hierarchical convention for specifying the style object and property you want to set:

    Control.StyleObject.Property = value
    
    Control.StyleObject.Property = value;
    

    The following code example shows how to set the BackColor property for the DayStyle object of a Calendar control:

    Calendar1.DayStyle.BackColor = System.Drawing.Color.Green
    
    Calendar1.DayStyle.BackColor = System.Drawing.Color.Green;
    

    You can also create a separate Style object and copy or merge the values of its properties to one of the styles on a control. This is a powerful way to apply the same styles to several different list objects in your project. In effect, you can create a virtual style sheet as a Style object and then apply it to a series of controls.

To create a style object and apply it to controls

  1. Create an instance of the Style object and set its properties, as shown in the following example:

    Dim s As Style = New Style()
    s.BackColor = System.Drawing.Color.Red
    
    Style s = new Style();
    s.BackColor = System.Drawing.Color.Red;
    
  2. Assign the Style object to a control using one of the following methods:

    • The CopyFrom method applies all settings from a Style object, including null ones.

    • The MergeWith method copies only the properties already set on the Style object, skipping Style properties that have not been set. Also, the MergeWith method will not overwrite any existing style elements.

    The following code example shows how you might create a Style object, set one of its properties, and then apply it to two different control style objects, using each of the methods described:

    ' Apply all values in s, including nulls.
    Calendar1.SelectedDayStyle.CopyFrom(s)
    ' Apply only values in s that are null in HeaderStyle.
    DataGrid1.HeaderStyle.MergeWith(s)
    
    // Apply all values in s, including nulls.
    Calendar1.SelectedDayStyle.CopyFrom(s);
    // Apply only values in s that are null in HeaderStyle.
    DataGrid1.HeaderStyle.MergeWith(s);
    

See Also

Tasks

How to: Set ASP.NET Server Control Style Properties Using ASP.NET Syntax

Concepts

ASP.NET Web Server Controls and CSS Styles