0

I'm using this code:

foreach (Control c in this.Controls)
{
  Button btn = c as Button;
  {
  if (c == null)
    continue;

  c.Click += handle_click;
  }

void handle_click(object sender, EventArgs e)
{
  Form1 ss = new Form1();
  ss.label1.Text = (sender as Button).Text;
  ss.ShowDialog();
}

But the code influence all my Form elements. Example all my buttons. How can create an exception for one button? I manage that by creating a panel and place my button inside, but when i'm clicking on the panel i get this error message:

"NullReferenceExeption was unhandled" "Object reference not set to an instance of an object"

Why this happen?

D Stanley
  • 149,601
  • 11
  • 178
  • 240
DmO
  • 357
  • 2
  • 14
  • Possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Ondrej Svejdar Apr 04 '16 at 19:45
  • It's not clear what the problem is or what you are trying to do - what do you mean by "create an exception for one button?" – D Stanley Apr 04 '16 at 19:46
  • I think my problem is that i try to pass value which is not exist into my panel. Example ss.label1.Text = (sender as Button).Text;. – DmO Apr 04 '16 at 19:47

1 Answers1

4

One problem is here:

  Button btn = c as Button;
  {
  if (c == null)  <-- should be if(btn == null)
    continue;

So you are assigning the event handler to every control, not just buttons. Then when you try to cast the sender to Button in the event handler you get a null value.

You could also afford to shore up your event handling in the event handler:

void handle_click(object sender, EventArgs e)
{
  var button = (sender as Button);
  if(button == null)
  {
      //throw an exception?  Show an error message? Ignore silently?
  }
  Form1 ss = new Form1();
  ss.label1.Text = button.Text;
  ss.ShowDialog();
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • Ok Thank you that was my ProBlem! You Solved it! Should i delete my answer for something so simple or just let it exist? – DmO Apr 04 '16 at 19:52
  • You can if you want, otherwise I will vote to close it for being a typo. – D Stanley Apr 04 '16 at 19:54