September 20, 2005

Using Web User Control

Note: Recommend Audience - Asp.net Beginner

Web user control is playing a major role in asp.net development. Its hardly possible to develop a application without web user controls. But most of developers are not using it properly. In this article I just thought to share some powerful features of web user control. Microsoft .Net framework is fully object oriented implementation. So we have to take advantage of it. We can learn lots of things by looking at the Microsoft class library. So lets start simple sample to show proper use of Web user control.

Scenario: We have to create 3(might be more) Registration forms in different formats. But the Mailing Address section is always stays the same. We need to accomplish this in minimum effort with a Web User Control in OOP manner.

Solutions: So lets start creating simple Web User Control name AddressUI;






In code behind of the AddressUI insert the below code

//AddressUI Properties
public string Street1
{
get {return this.txtStreet1.Text ;}
set {this.txtStreet1.Text = value;}
}

public string Street2
{
get {return this.txtStreet2.Text ;}
set {this.txtStreet2.Text = value;}
}
public string City
{
get {return this.txtCity.Text ;}
set {this.txtCity.Text = value;}
}
public string Country
{
get {return this.txtCountry.Text ;}
set {this.txtCountry.Text = value;}
}
public bool ContactMe
{
get {return this.chkContactMe.Checked ;}
set {this.chkContactMe.Checked = value;}
}


Now you can use this AddressUI control in any page u wanted. Giving u easily maintainable UI. Let me show you how u can use this control in your ASP.net pages.

Drag & drop the control into the page. You can access the controls property. Check the below code.

Declare the AddressUI control

protected AddressUI AddressUI1;

then access its properties, Add this code to a button click event.

Response.Write(AddressUI1.City + AddressUI1.Country );


your done. You can assign its properties to another objetecs properties.. no hassle doing Page.FindControl & no casting at all.

No comments: