Reputation:
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
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
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
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
Reputation: 19142
OnMyPropertyValueChanged
in fum.ascx.Upvotes: 4