Follow the steps below to create your first composite control:
1. Create a new class with a meaningful name
2. Import the following libraries (not all are needed but they will come in useful)
System.Web;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.HtmlControls;
3. Now make the class you have just created public and inherit from CompositeControl
public class MyControl : CompositeControl
3a. Add a label control to your composite control by overriding the CreateChildControls method in the body of your class.
protected override void CreateChildControls()
{
Label myLabel = new Label();
myLabel.text = "Hello world";
Controls.Add(myLabel);
base.CreateChildControls();
}
As you can see I have created a Label control, set the text "Hello world" and then added it to the pages Controls collection.
Any controls added to the Controls collection will be rendered in turn and as long as they are added to this collection they will be rendered.
3b. This alternative method is more of a raw and lower level way of creating content in your composite control
Instead of overriding the CreateChildControls method override the RenderContents method in the body of your class.
protected override void RenderContents(HtmlTextWriter output)
{
output.Write("Hello world");
}
Both of these methods achive exactly the same thing but are very different ways of doing things. and both have their advantages and disadvantages.
4. Now you have to add the control to a (*.aspx) web page so firstly register the assembly (your composite control). Below is an example but depending on how your project and namespace is named and arranged it will vary.
<%@ Register Assembly="MyControls" TagPrefix="MyControl" Namespace="MyControls" %>
5. Add the control to your page. Again the actual code witll vary depending on how you have named things but below is an exaple.
Now when you view your page in the browser "Hello world" should be written to the screen. Not very useful but shows the basics to creating your own composite controls.
No comments:
Post a Comment