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?
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?
OnMyPropertyValueChanged
in fum.ascx.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.
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.
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
Dim objParent As Object
Dim lngPropID As Long
objParent = Me.Parent.FindControl("fum")
lngPropID= objParent.PropID 'public property PropID on fum