Saturday, February 13, 2010

User Controls; the reusability!

You can call the same UserControls any number of times

In the ASPX file, reference goes as..




My User Control Code Behind does the job of fetching Latest News for Area.
It accepts AreaId and NewsCount(Number of Records) as input.

I am going to use this User Control to fetch Latest news for different areas.
Say, I wanted to display Bangalore, Hyderabad, and Delhi News.

Here All i need to do is to create a UserControl which accepts the paramenters AreaId and NewCount.

I can drag and drop this user control in the page three times to display the news for three Areas.

This is my UserControl CodeBehind file

public partial class News_UCLatestNews : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
BindDataList();
}
private Int64 areaId;
public Int64 AreaId
{
get { return areaId; }
set { areaId= value; }
}
private Int64 newsCount;
public Int64 NewsCount
{
get { return newsCount; }
set { newsCount = value; }
}
private void BindDataList()
{
List oList = new List();
NewsEntityShort oEntity = new NewsEntityShort();
NewsLogic oLogic = new NewsLogic();

oEntity.NewsCount = NewsCount;
oEntity.ParkId = AreaId;

oList = oLogic.GetNewsUpdatesForPark(oEntity);
DLLatestNews.DataSource = oList;
DLLatestNews.DataBind();

}
}

Note down, UserControl is not assigning values for AreaId and NewsCount. Instead, it declares these as PUBLIC propeties which can be added from any other page which make use of (consume) this User Control.

The code behind file of the Home page, where this user control has been dragged and dropped THREE times, will assign the AreaId and NewsCount for each UserControl.

The home page Code Behind will be as simple as this
protected void Page_Load(object sender, EventArgs e)
{
UCLatestNews1.NewsCount = 10;
UCLatestNews1.AreaId = 2; // Bangalore

UCLatestNews2.NewsCount = 10;
UCLatestNews2.AreaId = 3; // Hyderabad

UCLatestNews3.NewsCount = 5;
UCLatestNews3.AreaId = 4; // Delhi

No comments: