Getting Started: Creating SimpleControl

   

Getting Started: Creating SimpleControl

We're going to get started by creating a simple control that outputs a text string to the HTML stream. It has a single property with which the output string can be set, or the control can be used with the default string.

Take a look at the control's source code in Listing 13.1, and then I'll talk about it. This code would be found in your .cs source code file if you were adding a control to your project.

Listing 13.1 The Source Code for SimpleControl
 [DefaultProperty("Text"),      ShowInToolbox(true),      ToolboxData("<{0}:SimpleControl runat=server></{0}:SimpleControl>")]  public class SimpleControl : System.Web.UI.WebControls.WebControl  {      private string m_strText;      [Bindable(true),          Category("Appearance"),          DefaultValue("<h1>.NET Programming is cool.</h1>"),          Persistable(PersistableSupport.Declarative)]      public string Text      {          get          {              return m_strText;          }          set          {              m_strText = value;          }      }       protected override void Render(HtmlTextWriter output)      {          output.Write(Text);      }  } 

The Class and Its Attributes

Look first at the class declaration. Note that the class inherits from System.Web.UI.WebControls.WebControl , because this control is intended for use in an ASP.NET Web application. It's possible to inherit from Controls, but you don't get the support for HTML- related functionality if you inherit from Control. The following simple example shows the barest of Web controls, which inherits from System.Web.UI.WebControls.WebControl :

 public class BareControl : System.Web.UI.WebControls.WebControl  {  } 

You also probably noticed some attributes that precede the SimpleControl class. The first is the DefaultProperty attribute. This property specifies the default property for a component. The following example defines a control named MyControl . The class is marked with a DefaultProperty attribute that specifies MyProperty as the default property.

 [DefaultProperty("MyProperty")]  public class MyControl : Control  {      public int MyProperty      {          get          {              // Code here.          }          set          {              // Code here.          }      }      // Additional code.  } 

The next example creates an instance of MyControl . Then, it gets the attributes for the class, extracts the DefaultProperty attribute, and prints the name of the default property.

 public static int Main()  {     // Create a new control.     MyControl myNewControl = new MyControl();     // Get the attributes for the collection.     MemberAttributeCollection attributes = TypeDescriptor.GetAttributes( myNewControl );     // Print the name of the default property by retrieving the     // DefaultPropertyAttribute from the MemberAttributeCollection.     DefaultPropertyAttribute myAttribute =        (DefaultPropertyAttribute) attributes[typeof(DefaultPropertyAttribute)];     Console.WriteLine( "The default property is: " + myAttribute.Name );     return 0;  } 

Note

Attribute names used in your source code might be difficult to find in online help. For example, in this example you might not find DefaultProperty when you search MSDN. You can, however, find DefaultPropertyAttribute . When you get right down to it, an attribute eventually resolves to a method. And the convention now is to have a simplified attribute name, such as DefaultProperty or ThisColor , to be used in user 's source code, with method names having Attribute appended, as in DefaultPropertyAttribute and ThisColorAttribute .

In this book, I'll refer to attributes such as the DefaultProperty attribute. When I do, you'll know that the simplified name is DefaultProperty and the method probably is named DefaultPropertyAttribute .


If your control is to be used in a visual design environment, such as Visual Studio .NET, you must provide metadata that the designer needs to display your control correctly. The metadata is supplied by applying attributes to your control. Two attributes must be applied if a control is to be added to the toolbox of the Forms Designer in Visual Studio .NET. These are the ShowInToolbox attribute and the ToolboxData attribute. These attributes are applied at the class level (before the class declaration), as shown in the following example. The ToolboxData attribute is used to specify what will appear when a Web control is initially inserted into an .aspx page from the toolbox. For example, the following Web control:

 [ShowInToolbox(true)]  [ToolboxData("<{0}:ThisControl runat=server>Hi There</{0}:ThisControl>")]  public class ThisControl : System.Web.UI.WebControls.WebControl {...} 

inserts the following code into an .aspx Web form (more on the {0} and CustomControl items later, in the "Adding Custom Controls in the Toolbox" section):

 <CustomControl:ThisControl runat=server>Hi There</CustomControl:ThisControl> 

The Text Property

The SimpleControl class has a single property named Text . A get (sometimes called getter ) method enables users to retrieve the Text property, whereas a set (sometimes called setter ) method enables users to assign a value to the Text property. The Text property has several attributes that determine its behavior.

The Bindable attribute contains a value indicating whether a property is appropriate to bind data to. It evaluates to true if the property can be bound to data; otherwise , it is false.

The following example checks to see whether MyProperty is bindable. First, the code gets the attributes for MyProperty by retrieving a PropertyDescriptorCollection with all the properties for the object. Then it indexes into the PropertyDescriptorCollection to get MyProperty . Finally, it saves the attributes for this property in the attributes variable. The code then sets MyAttribute to the value of the BindableAttribute in the MemberAttributeCollection and checks whether the property is bindable.

 // Get the attributes for the property.  MemberAttributeCollection attributes =    TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;  // Check to see if the property is bindable.  BindableAttribute myAttribute = (BindableAttribute) attributes[typeof(BindableAttribute)];  if( myAttribute.Bindable )  {    // Code here.  } 

The Category attribute contains the name of the category for the property or event to which this attribute is bound.

You can create a DefaultValue attribute with any value. A member's default value typically is its initial value. A visual designer can use the default value to reset the member's value. For example, the following code sets the default value of MyProperty to false:

 [DefaultValue(false)]  public bool MyProperty  {       get      {          // Code here.      }      set      {          // Code here.      }  } 

The next example checks the default value of MyProperty . First, the code gets a PropertyDescriptorCollection with all the properties for the object. Next, it indexes into the PropertyDescriptorCollection to get MyProperty . Then, it returns the attributes for this property and saves them in the attributes variable. The example then prints the default value by retrieving the DefaultValue attribute from the MemberAttributeCollection and writing its name to the console screen.

 // Get the attributes for the property.  MemberAttributeCollection attributes =     TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;  // Print the default value by retrieving the DefaultValueAttribute  // from the MemberAttributeCollection.  DefaultValueAttribute myAttribute =     (DefaultValueAttribute)attributes[typeof(DefaultValueAttribute)];  Console.WriteLine( "The default value is: " + myAttribute.Value.ToString() ); 

When generating code, the value used to set persistence determines which aspects of the property or event are examined and saved. When you mark a property with this attribute, it is set to a constant member. When you want to check the value of this attribute in your code, you must specify the constant member. The constant member to which each value is set is listed in the Description column in Table 13.1.

Table 13.1. The Persistence Values

Persistence Value

Description

PersistableAttribute.None

The attribute is set to the constant member PersistableAttribute.None .

PersistableAttribute.All

This is the default. The attribute is set to the constant member PersistableAttribute.All .

PersistableAttribute.Resource

The attribute is set to the constant member PersistableAttribute.Resource .

PersistableAttribute.Code

The attribute is set to the constant member PersistableAttribute.Code .

PersistableAttribute.Declarative

The attribute is set to the constant member PersistableAttribute.Declarative .

PersistableAttribute.NotCode

The attribute is set to the constant member PersistableAttribute.NotCode .

PersistableAttribute.NotDeclarative

The attribute is set to the constant member PersistableAttribute.NotDeclarative .

   


Special Edition Using ASP. NET
Special Edition Using ASP.Net
ISBN: 0789725606
EAN: 2147483647
Year: 2002
Pages: 233

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net