Creating an event for a component. : User Control « GUI Windows Form « C# / C Sharp






Creating an event for a component.

 


using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;


public class CompoundControl : System.Windows.Forms.UserControl {
    public delegate Boolean ValueChangedEventHandler(int nValue);
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.ComboBox comboBox1;
    public event ValueChangedEventHandler Changed;

    public CompoundControl() {
        this.comboBox1 = new System.Windows.Forms.ComboBox();
        this.label1 = new System.Windows.Forms.Label();
        this.SuspendLayout();
        this.comboBox1.DropDownWidth = 121;
        this.comboBox1.Items.AddRange(new object[] {"A","B","C","F","G","N"});
        this.comboBox1.Location = new System.Drawing.Point(24, 48);
        this.comboBox1.Size = new System.Drawing.Size(200, 21);
        this.comboBox1.Text = "comboBox1";
        this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.OnSelectionIndexChange);
        this.label1.Location = new System.Drawing.Point(16, 24);
        this.label1.Text = "Select An Entry";
        this.Controls.AddRange(new System.Windows.Forms.Control[] {
        this.comboBox1,
        this.label1});
        this.Size = new System.Drawing.Size(240, 96);
        this.ResumeLayout(false);
    }
    private void OnSelectionIndexChange(object sender,
        System.EventArgs e) {
        if (Changed != null)
            Changed(this.comboBox1.SelectedIndex);
    }
}


public class Form1 : System.Windows.Forms.Form {
    private System.ComponentModel.Container components = null;
    private CompoundControl compoundcomponent1 = null;

    public Form1() {
        this.compoundcomponent1 = new CompoundControl();
        this.compoundcomponent1.Location = new System.Drawing.Point(24, 50);
        this.compoundcomponent1.Name = "compound1";
        this.compoundcomponent1.Size = new System.Drawing.Size(250, 100);
        this.compoundcomponent1.Changed += new CompoundControl.ValueChangedEventHandler(OnChanged);
        this.components = new System.ComponentModel.Container();
        this.Size = new System.Drawing.Size(300, 300);
        this.Controls.AddRange(new System.Windows.Forms.Control[]{this.compoundcomponent1,});
    }
    private bool OnChanged(int nIndex) {
        MessageBox.Show(this, "New Index!" + nIndex);
        return true;
    }

    [STAThread]
    static void Main() {
        Application.Run(new Form1());
    }
}

 








Related examples in the same category

1.subclass System.Windows.Forms.UserControl to create custom control
2.Draw a Custom Control
3.Define user controlDefine user control
4.The read-only property control.