Hi, a noob programmer just starting in C# with Visual Studio here....

I came across this while coding in Visual C# and I couldn't figure out anything about it so a little explanation would be greatly appreciated....

In Microsoft's Visual C#...when using Windows Forms for GUI.....

You guys know how there's a Design view and a Code view?,
and let's say you create a button1 on the Design view, and if you double click that on the Design view, Visual C# automatically generates an event handler linked to that button on the Code view like....

private void button1_Click(object sender, EventArgs e){
        }

this might be a dumb question but I tried copying that code above and just pasted it into the Code view INSTEAD of letting it generate from the doubl-clicking and when I ran the program, the button didn't work.........Why is that???
The button's function only works if I generate the code by double-clicking it....
I'm guessing when you double click the button there's more to it than just the code automatically being generated?

Any explanation would be great.

Thank you guys.

Recommended Answers

All 3 Replies

There's some other code generated that refers to the button1_Click method -- look around for it, it's probably folded up somewhere. I can guarantee that simply adding that method is unsufficient to put an event handler in place.

Edit:
Right click the method when it's auto-generated, and click "Find All References" -- that'll show you where the method is getting used.

this.button1.Click += new System.EventHandler(this.button1_Click);

this will do the trick for you ;)

If you've ever expanded the file for a form in the list view in your solution explorer pane, you should see two files below the main Form source file. There should be a [form_name].Designer.cs (or whatever language). Inside that file is where it handles setting all of the properties for your controls. This is also where the event handlers get wired up as mentioned in the other posts.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.