User Controls are used very often nowadays. All those controls that would appear on various places as a group are placed as a user control and used as a single control. As the usage becomes easy there are few problems along with this.
The following example explains one such problem and a solution for the same.
An aspx page, say main.aspx, contains three user controls say A,B and C and one button(btnSave) to save the changes. A and B contains various input elements like textboxes and drop down lists. C contains a link which will navigate to some page.
When the user clicks on btnSave the data from A and B are saved to the database. Now what if the user clicks on a link on C, without saving the data? This results in a data loss as the user is redirected to some page without saving the data. This has to be handled in the code to avoid data loss.
The approach would be to save the data on clicking the link button. But how to save data present in other user control from one user control? It is achievable but one has to rewrite the code. To avoid this rewritting, we can make use of events and solve the issue.
The approach is to raise an event from the user control on clicking the link button which will call the btnSave_Click method in the aspx page. This results in saving time for rewritting the code.
following is the code to create an event.
public event EventHandler userControl_event;
this eventHandler will be used to call the btnSave_Click event present in the aspx page.
to associate the btnSave_Click to the user controls eventhandler we have to add the following to the aspx page ( adding to the page_load method will be better)
this.userControlC.userControl_event += new EventHandler(btnSave_Click)
now to raise the event we have to add the following code to the link button's Click event
userControl_event(sender,e);
So, the code of the aspx page and the userControlC will look like following
main.aspx
------------
public partial class main_class
{
protected void Page_Load (object sender, EventArgs e)
{
this.userControlC.userControl_event += new EventHandler(btnSave_Click);
}
protected void btnSave_Click(object sender, EventArgs e)
{
/// User Code to save the data from other user controls
}
}
usercontrolC.ascx
-----------------------
public partial class usercontrolC
{
public event EventHandler userControl_event;
protected void Page_Load (object sender, EventArgs e)
{
}
protected void linkButton1_Click(object sender, EventArgs e)
{
userControl_event(sender,e);
}
}
Saturday, June 13, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment