Monday, April 26, 2010

Custom Event Handling in C Sharp .NET

Hi,

This is the good example for Event handling mechanism with system events.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace eventmgmt
{
public delegate void NameButtonClicked(object sender, EventArgs e);

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int txt_val1, txt_val2;
TextBox txt1 = new TextBox();
TextBox txt2 = new TextBox();
TextBox txt3 = new TextBox();
Button btn = new Button();
private void Form1_Load(object sender, EventArgs e)
{
Label lbl1 = new Label();

lbl1.Text = "Enter A value";
lbl1.Location = new Point(0, 100);

txt1.Location = new Point(100, 100);
txt1.Text = "";

Label lbl2 = new Label();
lbl2.Text = "Enter B value";
lbl2.Location = new Point(0, 150);

txt2.Location = new Point(100, 150);
txt2.Text = "";

Label lbl3 = new Label();
lbl3.Text = "A + B is";
lbl3.Location = new Point(0, 170);

txt3.Location = new Point(100, 175);

btn.Location = new Point(100, 225);
btn.Text = "add";

this.Controls.Add(lbl1);
this.Controls.Add(txt1);
this.Controls.Add(lbl2);
this.Controls.Add(txt2);
this.Controls.Add(lbl3);
this.Controls.Add(txt3);
this.Controls.Add(btn);

btn.Click += new System.EventHandler(NameButtonClicked);

}
public void NameButtonClicked(object sender, EventArgs e)
{
txt_val1 = Convert.ToInt32(txt1.Text);

txt_val2 = Convert.ToInt32(txt2.Text);
txt3.Text = (txt_val1 + txt_val2).ToString();
}

}
}

No comments:

Post a Comment