I created a new Windows Forms Control Library and created 2 different user controls. I imported the controls to my main form on another project and am able to access controls when I create them.
UserControlType1 uc1 = new UserControlType1();
UserControlType2 uc2 = new UserControlType2();
The controls both have a Status property I can access on the form. I can access the status from each individually.
Debug.Print(uc1.Status);
Debug.Print(uc2.Status);
But is there a way I can access that status from an array of different user controls or some other way? I plan on having 2 dozen or more different user controls and would like to reference them by index depending on which tab on the main form is active. I'm new to user controls, what approach should I take?
object[] uc_array = new object[2]{uc1, uc2}; // unable to access properties
CodePudding user response:
I ended up creating a support class inherited by all the different usercontrols. In the main form I created a new array of these types and populated them.
UserControlType1 uc1 = new UserControlType1();
UserControlType2 uc2 = new UserControlType2();
Support[] supp_ar = new Support[2]{uc1.Properties, uc2.Properties};
Debug.Print(supp_ar[0].Status); // does now show the status
CodePudding user response:
I'm in agreement with Fildor's comment because implementing an interface
can be quite a bit more flexible and extensible. There's no requirement to inherit any particular base class, and it's possible to mix-and-match interfaces as a form of de facto multiple inheritance. In this case, it might be especially useful to include an event
so the UserControl
can notify the parent when something happens that might require a status update.
interface IStatusProvider
{
string Status { get; }
event EventHandler StatusUpdated;
}
Example of a `CustomUserControl : UserControl, IStatusProvider
class UserControlTypeA : UserControl, IStatusProvider
{
public UserControlTypeA()
{
_checkBox =
new CheckBox
{
Text = "CheckBox",
Size = new Size(150, 50),
TextAlign = ContentAlignment.MiddleCenter,
Appearance = Appearance.Button,
};
_checkBox.CheckedChanged = (sender, e) =>
StatusUpdated?.Invoke(this, EventArgs.Empty);
Controls.Add(_checkBox);
AutoSizeMode = AutoSizeMode.GrowAndShrink;
AutoSize = true;
}
private readonly CheckBox _checkBox;
public event EventHandler StatusUpdated;
public string Status => $"{GetType().Name}: {_checkBox.Checked}";
}
Make a collection of them like this:
IStatusProvider[] UserControls = new IStatusProvider[]
{
new UserControlTypeA(),
new UserControlTypeB(),
new UserControlTypeC(),
};