To Get USER CONTROLS Inter Page


First Way-

The current project I'm working on allows UserControls to be dynamically added to a page in a number of different placeholders across what could be an infinite number of templates. So basically using a CMS.

Awesome I hear you say but what happens when I want two of these UserControls to talk to each other? i.e. A search form control and a search results control. This was the problem I tackled recently and came up with a solution I'm reasonably happy with but thought I'd float it out there and see what you all think.

Firstly, I quickly decided to ignore the FindControl method, any solution I could think of involving it got messy and made me die a little inside.

EDIT: The decision to not use FindControl is due to the fact it only searches through the Control's child control collection and thus would require looping through controls to find the one I want.

This is what I have so far: Added a global public property to my base page class called BasePage:

public SortedList<string, CustomUserControl> CustomControls { get; set; } 

Added a public property to my base user control class called CustomUserControl:

protected SortedList<string, CustomUserControl> CustomControls 
{ 
    get  
    { 
        BasePage page = Page as BasePage; 
        if (page != null) 
            return page.CustomControls; 
        else 
            return null; 
    } 
} 

On the Page_Init of my UserControls added a reference to the control to the CustomControl collection, which assigns it to the property of the BasePage.

I can then access my UserControls from either the Page or the controls themselves using the CustomControl method, like such:

if (this.CustomControls.ContainsKey("SearchForm")) 
    searchForm = this.CustomControls["SearchForm"] as SearchForm; 

Thats the basics of it, am refining it as write this so please feel free to pick it apart. If any of you have a better/alternative solution I'd love to hear it. Or even if you've read an article on the problem, Google didn't help me much in my searches.


Second Way-



1.) You need to declare a Delegate. 

view plaincopy to clipboardprint?

// In event communication, the event sender class does not know which object or method will receive (handle) the events it raises.   

// What is needed is an intermediary (or pointer-like mechanism) between the source and the receiver.   

// The .NET Framework defines a special type (Delegate) that provides the functionality of a function pointer.  

// A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class has a signature,   

// and it can hold references only to methods that match its signature.  

public delegate void SearchCompletedEventHandler(object sender, SearchCompletedEventArgs e);  

       // In event communication, the event sender class does not know which object or method will receive (handle) the events it raises.

       // What is needed is an intermediary (or pointer-like mechanism) between the source and the receiver.

       // The .NET Framework defines a special type (Delegate) that provides the functionality of a function pointer.

       // A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class has a signature,

       // and it can hold references only to methods that match its signature.

       public delegate void SearchCompletedEventHandler(object sender, SearchCompletedEventArgs e);


2.) You will need to define the EventArgs object you wish to pass along to anything which subscribes to this event (the eventargs will contain the values we wish the other controls to have access to)

public class SearchCompletedEventArgs : EventArgs  

{  

    // this is a string value I will set using a dropdownlist  

    public string FileType { get; set; }  

    // this is a numeric value I will set using a textbox or a Telerik Numeric Textbox  

    public Int64 LoanNumber { get; set; }  

}  


3.) You will need to define the Event, whose Type will be of the Delegate you created.

// An event is a message sent by an object to signal the occurrence of an action.   

// The action could be caused by user interaction, such as a mouse click, or it could be triggered by some other program logic.   

// The object that raises (triggers) the event is called the event sender.  

public event SearchCompletedEventHandler SearchCompleted;  


4.) You need to trigger the event (in my case, it's when the user clicks the btnSearch button

       protected void btnSearch_Click(object sender, EventArgs e)

       {

           if (Page.IsValid)

           {               

               // checks to see if the event has been subscribed to

               // either codebehind (eventhandler += event(blah, blah)

               // or the aspx markup (OnClick="SearchCompleted")

               // this would be null if it wasn't subscribed to somewhere

               if (this.SearchCompleted != null)

               {

                   // Instantiate the eventargs we are going to pass through the event

                   SearchCompletedEventArgs args = new SearchCompletedEventArgs();\

                   // populate the properties of the eventarg object

                   args.FileType = ddlFile.SelectedValue;                   

                   args.LoanNumber = Convert.ToInt64(txtLoanNumber.Text);

                   // trigger the event!

                   this.SearchCompleted(this, args);

               }

           }

       }

5.) You need to Subscribe to the event (because my event is Public, it should be visible to anycontrol within it's vision.

   public partial class Event_Subscriptions : System.Web.UI.Page

   {

       protected void Page_Load(object sender, EventArgs e)

       {

           // subscribe to the event in codebehind

           ucSearch1.SearchCompleted += new Wils.Toolbox.UserControls.ucSearch.SearchCompletedEventHandler(ucSearch1_SearchCompleted);

           // alternatively, we could also subscribe using code in the ASPX page like...

           // OnClick="SearchCompleted"

       }


       // here is my event handler for the usercontrol event

       void ucSearch1_SearchCompleted(object sender, Wils.Toolbox.UserControls.SearchCompletedEventArgs e)

       {

           // do something here... this is the method which will run when the event is handled

           // AKA: The Event Handler

           throw new NotImplementedException();

       }

   }



Way Three-


Introduction

Always there comes a requirement where we developers need to pass values to between different user controls which are parts of a webpage or even sometimes there comes a requirement where we need to pass values from user control to the container page.

The job is easy when we have to pass values which are there on the user controls by exposing the value fields as properties of the user control. However it is challenging when on certain event the values should get passed.

Solution

The simplest solution to this situation I found is to handle this by use of events and delegates. Let me explain the solution with one simple example.

For example on a content page I am having 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:

citiesSelected(selectedCities);

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;

       ListBoxSelectedCities.DataBind();

   }

}

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;

}


要查看或添加评论,请登录

Rohit Gupta PMP?的更多文章

社区洞察

其他会员也浏览了