I have been working on a project that uses a lot of UserControls. Often, multiple UserControls are loaded onto the same Page. And in some cases, what is processed on the PostBack of one userControl has a direct effect on the data displayed on the base page or another UserControl. The problem is that the Page and UserControls have already loaded and run through their Page_Load events. How do you handle this?
Answer: Custom EventsActually, it's very simple. This article explains the most common scenario.
Users tab:
Tasks tab:
Problem: We have a base Page that holds two UserControls: Users and Tasks (see above). Our Users UserControl allows the users to be added/updated/deleted. The Tasks UserControl allows tasks to be created and assigned to users. When the Page loads for the first time, both UserControls are loaded for the first time and their dropdownlists are also loaded once (including the list of users on the Tasks UserControl).
On subsequent posts, the Page.IsPostBack property is checked and the trips to the database are saved. When a user is added on the Users UserControl, the cmdSave (Save button) event triggered and the user is added to the database...but it isn't reflected in the Tasks UserControl. Here's what needs to be done:
1. Users UserControl code - Declare a custom event (UCUpdated) and a generic method (RaiseUCUpdatedEvent) to call to fire the event. When appropriate, call RaiseUCUpdatedEvent. In the example below, a user is deleted so we must refresh the tasks' users dropdownlist otherwise we'll get referencial integrity errors when trying to assign a task to the deleted user.
1//Declare event2publicevent CommandEventHandler UCUpdated;
34//Method to fire event5privatevoid RaiseUCUpdatedEvent(string strMessage)
6{
7 CommandEventArgs args = new CommandEventArgs("UCUpdated", strMessage);
8 UCUpdated(this, args);
9}
1011//Sample code that triggers the event to fire12objDataSvc.DeleteProjectUsers(intProjectUserID);
13if (objDataSvc.ErrorCode == 0)
14{
15 lblMessage.Text = "Delete successful!";
16 RefreshDataGrid();
17 RaiseUCUpdatedEvent();
18}
192. Page code - In the Page_Load event, add an event handler for the Users UserControl UCUpdated event that references a private method. In the example below, we simply call the public method "Load ProjectUsers()" in the Tasks UserControl. This method clears the dropdownlist and loads the current project users (same method called in the Tasks UserControl's Page_Load when Page.IsPostBack is false.
1//Page_Load - add event handler2privatevoid Page_Load(object sender, System.EventArgs e)
3{
4 ucProjectUsers.UCUpdated += new System.Web.UI.WebControls.CommandEventHandler(ucProjectUsers_UCUpdated);
5}
67//Event handler8privatevoid ucProjectUsers_UCUpdated(object sender, System.Web.UI.WebControls.CommandEventArgs e)
9{
10 ucProjectTasks.LoadProjectUsers();
11}
12
Comments
|
On
1/8/2010
Ruben
said:
I tried the code, but visual studio automatically copies my the line:
|
Leave a Comment