C#.NET: How to update multiple .NET pages when a particular event occurs in one .Net page? In another words how to use Observer pattern(Publish and subscribe to events)

Posted on Microsoft .NET Support Team See other posts from Microsoft .NET Support Team
Published on Tue, 29 Jun 2010 13:07:00 +0000 Indexed on 2011/01/11 9:57 UTC
Read the original article Hit count: 175

Filed under:

Problem: Suppose you have a scenario in which you have to update multiple pages when an event occurs in main page. For example imagine you have a main page where you are dispalying a tab control. This tab control has 3 tab pages where you are loading 3 different user controls. On click of an update button in main page imagine if you have do something in all the 3 tab panels. In other words an event in main page has to be handled in many other pages. An event in main page which contains the tab control has to be handled in all the tab panels(user controls)

Answer: Use Observer pattern

Define a base page for the page that contains the tab control.

Main page which contains the tab: Baseline_Baseline

Basepage for the above main page: BaselineBasePage

User control that has to be udpated for an event in main page: Baseline_PriorNonDeloitte

Source Code:

public class BaselineBasePage : System.Web.UI.Page

{

IList lstControls = new List();

public void Add(IObserver userControl)

{

lstControls.Add(userControl);

}

public void Remove(IObserver userControl)

{

lstControls.Remove(userControl);

}

public void RemoveAllUserControls()

{

lstControls.Clear();

}

public void Update(SaveEventArgs e)

{

foreach (IObserver LobjControl in lstControls)

{

LobjControl.Save(e);

} } }

public interface IObserver

{

void Update(SaveEventArgs e);

}

public partial class Baseline_Baseline : BaselineBasePage

{

. .

.

this.Add(_ucPI); this.Add(_ucPI1);

protected void abActionBar_saveClicked(object sender, EventArgs e)

{

SaveEventArgs se = new SaveEventArgs();

se.TabType = (BaselineTabType)tcBaseline.ActiveTabIndex;

this.Update(se);

}

}

Public class Baseline_PriorNonDeloitte : System.Web.UI.UserControl,IObserver

{

public void Update(SaveEventArgs e)

{

}

}

More info at:

http://www.dofactory.com/Patterns/PatternObserver.aspx

© Microsoft .NET Support Team or respective owner

Related posts about Design Patterns