Thursday, May 12, 2005

How User Controls Communicate in ASP.NET1.1

ASP.Net has a good support for component oriented programming. Even the User controls can be excellect self independent components. A user control can not only have public methods & properties, it can also have events. Using this concepts we can easily decompose any complex page to simpler user controls ,ie., I mean to say don't hesitate to create usercontrols to split a complex page, even if the usercontrols is used only once.

Now Let's look at how user controls communicate using events.

First we will see how to add an event to a user control "Header"

  1. Add delegate declaration in the namespace
  2. Add event declaration in the class
  3. Fire the event



namespace TestUserControl
{
public delegate void ChangeEventHandler(
object sender, string ID);
public class Header : Web.UI.UserControl
{
protected WebControls.Label lblApp;

public event ChangeEventHandler Change;

public void ChangeAppName(string AppName)
{
this.lblApp.Text =AppName;
Change (this,"Changed appname to : "
+ AppName.Trim().ToUpper());
}
}
}



Now Lets see how to consume the
event in a page


namespace TestUserControl
{
public class WebForm1 : System.Web.UI.Page
{
protected WebControls.Button Button1;
protected WebControls.TextBox TextBox1;
protected Header hdr;

private void Page_Load(object sender,
System.EventArgs e)
{
hdr.Change+= new
ChangeEventHandler(hdr_ChangeEvent);
}
private void Button1_Click(object sender,
System.EventArgs e)
{
hdr.ChangeAppName("New Application"
+ TextBox1.Text);
}
private void hdr_ChangeEvent(object sender,
string ID)
{
TextBox1.Text= ID;
}
}
}

Note: Only relevent code has been kept,
place the code in the appropriate area.

4 comments:

Anonymous said...

very helpful.

Anonymous said...

I got Errro with ChangeEventHandler not declare in .aspx page..
tell me how i can solve this .

otherwisw It's really Helpful ..

Prashant said...

always verify if (Change!=null) before calling if are not sure to have an a handler.

I apretiate you to point this out.

Anonymous said...

Hi..
I am trying to develop an editable datagrid/gridview for around 15000 Concurrent users.
my limitation are :
-can use framework 1.0/1.1 only.

can you please suggest a code.

thanx in advance..