Friday, September 17, 2004

Simple Events

If you haven't read the previous post, I hope you read it first.

The way C# Handles events is very clear. You first instantiate the component:

this.button1 = new System.Windows.Forms.Button();

Next, add it to the container. In this case I just add it to a groupBox component. I will have to add the groupBox to the Form of course. Actually, by using C# Builder this is all done automatically :-)

This code below sets the button properties and the last line is the one that matters:

this.button1.Location = new System.Drawing.Point(152, 16);
this.button1.Name = "button1";
this.button1.TabIndex = 0;
this.button1.Text = "Calculate";
this.button1.Click += new System.EventHandler(this.button1_Click);

By doing it, the compiler knows that you created an Event to the component. The Click event is the one in this case.

With Java, you would have a real complicated task for adding a handler, by either using an inner class or creating a separate class. With C# it gets easy:

private void button1_Click(object sender, System.EventArgs e)
this.label1.Text = this.textBox1.Text;

The System.EventHandler( ) class recieves as parameter the method implemented above. It simply passes the value in a textfield to a label whenever you click the button. If you know me, this the program I always to when learning GUI programming for a certain language. :-)

No comments: