This is easy example for Custom Events Handling.
1.Create a form with two label and two text box and two button with the text "Add" and "Clear"
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 CustomEvents2
{
    public delegate void MyCustomEvents(string target);
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public int txt_val1, txt_val2;
        public int aval, bval;
        TextBox txt1 = new TextBox();
        TextBox txt2 = new TextBox();
        TextBox txt3 = new TextBox();
        Button btn = new Button();
        public event MyCustomEvents MyEvents;
        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);
        }
    public class MyButttonEvent : Button 
    {
        //constructors
        public MyButttonEvent()
        {
            // this.Click += new MyCustomEvents(this,m1.Addition);
        }                                                                                                
    }
   private void button1_Click(object sender, EventArgs e)
    {
        aval = Convert.ToInt32(txt1.Text);
        bval = Convert.ToInt32(txt2.Text);
       this.MyEvents += new MyCustomEvents(Addition);
        if (aval != 0 && bval != 0)
            if (this.MyEvents != null)
                this.MyEvents("add");
    }
   public void Addition(string t)
   {
       txt_val1 = Convert.ToInt32(txt1.Text);
       txt_val2 = Convert.ToInt32(txt2.Text);
       txt3.Text = (txt_val1 + txt_val2).ToString();
   }
   private void button2_Click(object sender, EventArgs e)
   {
       txt1.Text = "";
       txt2.Text = "";
       txt3.Text = "";
   }
  }                            
}
No comments:
Post a Comment