how to ceate event_click for button with C# ? [modified]
-
my code is here . what is the misstake ? it error when click on that button and message that "the object reference not set to an instand of an object". please give me some help void Button_Click(object sender, EventArgs e) { Button clickedButton = sender as Button ; if (clickedButton.Name == "Program") { MessageBox.Show("lkjd;lfjal;sdkjf;laksdjfl;jasd"); } else { MessageBox.Show("dddddddddddddddd"); } }
modified on Thursday, May 21, 2009 3:27 PM
-
my code is here . what is the misstake ? it error when click on that button and message that "the object reference not set to an instand of an object". please give me some help void Button_Click(object sender, EventArgs e) { Button clickedButton = sender as Button ; if (clickedButton.Name == "Program") { MessageBox.Show("lkjd;lfjal;sdkjf;laksdjfl;jasd"); } else { MessageBox.Show("dddddddddddddddd"); } }
modified on Thursday, May 21, 2009 3:27 PM
Hi, if that handler gets connected to an event of something other than a Button, then
Button clickedButton = sender as Button ;
will set clickedButton to null. You can take care of that by changing your code to:...
if (clickedButton!=null && clickedButton.Name == "Program")
...or by making absolutely sure only Buttons are being wired up to this handler. FWIW: the fact that the handler's name starts with "Button" is fine for readability but does not change the way the code works. :)
Luc Pattyn [Forum Guidelines] [My Articles]
The quality and detail of your question reflects on the effectiveness of the help you are likely to get. Show formatted code inside PRE tags, and give clear symptoms when describing a problem.
-
my code is here . what is the misstake ? it error when click on that button and message that "the object reference not set to an instand of an object". please give me some help void Button_Click(object sender, EventArgs e) { Button clickedButton = sender as Button ; if (clickedButton.Name == "Program") { MessageBox.Show("lkjd;lfjal;sdkjf;laksdjfl;jasd"); } else { MessageBox.Show("dddddddddddddddd"); } }
modified on Thursday, May 21, 2009 3:27 PM