Re: Basic Newbie question



Hi,

Anil Gupte wrote:
I am learning to use C#, having decided to upgrade myself from VB.Net (to which I also recently upgraded a few months ago from VB6).

I created a Windows Application and in it a form. I added a label and a button on the form. Then I double-clicked on the button and added the following:
private void button1_Click(object sender, System.EventArgs e)

{

lblTest.Text="Hello World!";

}

As I usually do in VB, I changed the button name from button1 to btnTest in the Properties window. Now I have an error saying:

C:\Projects\vbtut\WindowsApplication1\Form1.cs(74): 'WindowsApplication1.Form1' does not contain a definition for 'button1_Click'

Why should it still be looking for button1, when I have gone in and changed it. In VB I don't have this problem, what gives?

Thanx,

When you create a button, you must rename it first and then only double-click it to add event handlers.

When you double-click the button, it adds an entry in the "InitializeComponent" method, something like:

button1.Click += new EventHandler( button1_Click );

This is called a delegate, it means that you add a reference to your method "button1_Click" (as if it was an object) to the list of methods which will be executed when the "Click" event fires.

If you rename the "button1" in "btnTest", and especially if you rename the method "button1_Click" to "btnTest_Click", then you must also modify the delegate definition:

btnTest.Click += new EventHandler( btnTest_Click );

It's a bit tricky to understand how delegate work, but I recommend you to study that carefully, because they are an invaluable help, for example for multithreading.

HTH,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
.