FooFum
FooFum

Reputation:

ASP.NET User Controls Cross-Communication

The scenario: 2 user controls (foo.ascx and fum.ascx)

foo has a method that would really like to access a property from fum. They live on the same page, but I can't find a very simple way to accomplish this sort of communication.

Any ideas?

Upvotes: 2

Views: 3678

Answers (5)

Ricomyer
Ricomyer

Reputation:

You can reference the other user control by using FindControl on Foo's Parent. This is the simplest and you don't need to program anything on each main (parent) form.

'From within foo...call this code<br>
Dim objParent As Object<br>
Dim lngPropID As Long<br>

objParent = Me.Parent.FindControl("fum")<br>
lngPropID= objParent.PropID 'public property PropID on fum<br>

Upvotes: 0

FlySwat
FlySwat

Reputation: 175573

There are a few ways to handle this, but optimally you want a solution that is as decoupled as possible.

The most decoupled method would be a recursive findControl method that walks the control object model until it finds the control you want and returns a reference.

private Control findControl(Control root, string id) 
{ 
    if (root.ID == id)
    { 
        return root; 
    } 

    foreach (Control c in root.Controls) 
    { 
        Control t = findControl(c, id); 
        if (t != null) 
        { 
            return t; 
        } 
    } 

    return null; 
}

Here is another approach that is kinda neat, though I don't know if I'd use it.(Somewhat pseudocode):

public FunkyUserControl : UserControl
{
    private List<UserControl> subscribedControls;

    public List<UserControl> Subscribers
    {
        get { return subscribedControls;}
    }

    public void SubscribeTo(UserControl control)
    {
        subscribedControls.Add(control);
    }
}

Inherit your two usercontrols from FunkyUserControl and then in your main page class you can do:

webControl1.SubscribeTo(webControl2);
webControl2.SubscribeTo(webControl1);

Now each control can introspect its subscribers collection to find the other control.

Upvotes: 1

stevemegson
stevemegson

Reputation: 12093

The simplest solution is for fum to store a value in HttpContext.Current.Items[], where foo can read it later.

A more robust option is to give foo a property that the the page can populate with a reference to fum.

An event is more work, but is architecturally nicer.

Upvotes: 0

Panos
Panos

Reputation: 19142

  • Add an event OnMyPropertyValueChanged in fum.ascx.
  • Add the corresponding EventHandler to foo.ascx which stores the property value in a private variable.
  • Attach the event handler of foo.ascx to the event of fum.ascx on Page_Load.
  • Raise the event on fum.ascx Page_Load and whenever needed
  • Let the method of foo.ascx use its own variable

Upvotes: 4

Craig
Craig

Reputation: 36816

Add an event to the UserControl that is hooked up to the form.

Upvotes: 0

Related Questions