Passing Values between User Controls using Events and Delegates

On a content page there are two user controls e.g. UC1 and UC2. Contents of UC1 are:
1. List box having list of States
2. List box having list of Cities in the State (Pre-condition: User selects State from ListBoxStates and respective cities in the selected state gets populated in the ListBoxCities)
3. Button control, which will be used for confirming the user’s selections. Let us name it as btnSelect.
Contents of UC2 are:
1. List of selected cities from UC1. Let us name it as ListBoxSelectedCities.
Our requirement is whenever user selects (multiple) cities from ListBoxCities and clicks on btnSelect in UC1 then the selected cities should get populated in ListBoxSelectedCities in UC2.

In UC1, we need to declare the following objects:

public delegate void PassSelectedValues(string[] selectedCities);
public event PassSelectedValues citiesSelected;

Now in UC1 from the button click event we can raise citiesSelected event, delegate of which will carry the required values which we need to pass in between UC1 and UC2. In button click event we have to create the list of selected cities from ListBoxCities and we have to raise the citiesSelected event like this:


Here selectedCities is an array of strings which we have to create by looping through the ListBoxCities.
We have to declare a public property in UC2 which can be used to set the ListBoxSelectedCities. For example in UC2:

public string[] SelectedCitiesList{
set { ListBoxSelectedCities.DataSource = value;

In the content page we have to declare the event handler for the event (citiesSelected) which we have raised from UC1. Thus in content page on page load we have to declare the handler of this event like this:

UC1.citiesSelected += new citiesUserControl.PassSelectedValues(passValuesHandlerMethod);

This handler method in the content page should have the same signature as of the delegate’s signature defined in UC1.

protected void passValuesHandlerMethod(string[] selectedCities){ }

Now from this method we can pass the value coming from UC1 to UC2 like this:

protected void passValuesHandlerMethod(string[] selectedCities){
UC2.SelectedCitiesList = selectedCities;

In this way whichever values we are selecting in UC1 will get passed to UC2.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s