-2

I have a custom control (UserControl) that contains two labels and a button, I load this control dynamically in a form. When I click on the custom control button, I would like to get the information contained for example in the label1 of the custom control.

    private void mycustomcontrol_MouseClick(object sender, MouseEventArgs e)
    {
        if(e.Button == MouseButtons.Left)
        {
            mycustomcontrol = sender as mycustomcontrol;
            MessageBox.Show(mycustomcontrol.Info); // <-- mycustomcontrol.Info refers to the label1 text on the custom control
        }
    }

In my Usecontrol:

    public new event MouseEventHandler MouseClick
    {
        add
        {
            button1.MouseClick += value;
        }
        remove
        {
            button1.MouseClick -= value;
        }
    }

I get an exception: System.NullReferenceException: 'Reference to an object not set to an object instance.'

  • 4
    Looks like the `sender` is not really a `mycustomcontrol`. Use the debugger in the line before to have a look at the `sender`! There seems to be some confusion about what is clicked, the control or the button or else why are you note coding its Clicked evnt?. Btw: It also looks as if you do __not__ have a __CustomControl__ (wich is a __subclass__ of some control) but a __UserControl__, which is a container, much like a Form. All events in a Usercontrol must be coded in its code, not in theForm's code after you have dropped it there.. If I am right I recomend to correct the misnomer! – TaW Feb 22 '21 at 12:26
  • The custom control is coded so that the click is valid only for the button on the container. – Synthwave1990 Feb 22 '21 at 12:41
  • And yes, mycustomcontrol is a UserControl – Synthwave1990 Feb 22 '21 at 12:46
  • How does the control raise the `MouseClick` event? – Alejandro Feb 22 '21 at 12:57
  • 1
    The sender may be the button the user have clicked, not the (parent) control. Therefore `sender as mycustomcontrol`returns `null`. – G Wimpassinger Feb 22 '21 at 13:03
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Ian Kemp Feb 22 '21 at 13:16
  • 2
    __Use the debugger in the line before to have a look at the sender!__ – TaW Feb 22 '21 at 13:32

1 Answers1

0

unorthodox solution, but in my case it's fine:

In my UserControl:

    public static string _value{ get; set; }
    private void Button1_MouseClick(object sender, MouseEventArgs e)
    {
        if(e.Button == MouseButtons.Left)
        {
            _value = lbl_info.Text;
        }
    }

In my Form:

private void mycustomcontrol_MouseClick(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Left)
    {
         MessageBox.Show(mycustomcontrol._value);
    }
}