Search code examples
c#winformscomposite-controls

C# Composite Control will lose name at design and run time


I developed a composite control using C# Windows Forms Control Library and code as follow:

public partial class MyControl : UserControl
{
    public event EventHandler NameChanged;
    protected virtual void OnNameChanged()
    {
        EventHandler handler = NameChanged;
        if (handler != null) handler(this, EventArgs.Empty);
    }

    private void WhenNameChanged(object sender , EventArgs e)
    {
        this.myGroupBox.Text = this.Name;
    }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();

        IComponentChangeService changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService));
        if (changeService == null) return; // not provided at runtime, only design mode

        changeService.ComponentChanged -= OnComponentChanged; // to avoid multiple subscriptions
        changeService.ComponentChanged += OnComponentChanged;
    }

    private void OnComponentChanged(object sender, ComponentChangedEventArgs e)
    {
        if(e.Component == this && e.Member.Name == "Name")
        {
            OnNameChanged();
        }
    }

    public MyControl()
    {
        InitializeComponent();
        this.NameChanged += new EventHandler(this.WhenNameChanged);
    }
}

The MyControl only has one GroupBox control named myGroupBox

private System.Windows.Forms.GroupBox myGroupBox;

I have a test program which is a C# Windows Forms Application, and I would like to see that when I change the name of myGroupBox in properties window, the text of myGroupBox will be the name I typed. so I typed a name Value to myGroupBox in the properties window, the text will change in designer, here is the screenshot: enter image description here

But when I rebuild the test program or at run time the text of myGroupBox will disappear, here is the screenshot:

enter image description here

what should I do with my code? thanks


Solution

  • So the problem is that the Name of a Control (or UserControl) is empty after construction. The name given by you and stored in the resources will be set in OnLoad.
    So a solution for you could be to override OnLoad with something like this:

    public class MyControl : UserControl
    {
        // ... the code so far
    
        // override OnLoad
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            myGroupBox.Text = Name; // or WhenNameChanged(this, EventArgs.Empty);
        }
    }
    

    So the name taken from the resources (e.g. after rebuild/reopen designer) will be set here again and so also set as myGroupBox.Text.

    Hope that helps.