⌘BABAKOV.NET Let's code!
100% [dark] [ru]

Programmatic Adding Events to Controls in C#

There are often cases when creating an event for controls programmatically is necessary, for example, when we need to perform certain manipulations with elements and data they contain before events are processed. This can be on change of selected value, mouse click, change of content, and many other events. It is advisable to create events programmatically rather than in the designer. I will show how to do this in an example.

DataSet ds = new DataSet(); //Создаем источник данных.
EventHandler handler; //Создаем делегат.


Now, when the form is loaded, we fill the ComboBox with data:

private void Form1_Load(object sender, EventArgs e)
{
ds.ReadXml("dataset.xml");
comboBox1.DataSource = ds.Tables["Table"].DefaultView;
comboBox1.ValueMember = "ID_DOCHEAD";
comboBox1.DisplayMember = "NAME";
}

Filling occurs from an XML file.

private void do_on_event(object sender, EventArgs e)
        {
            label1.Text = comboBox1.SelectedValue.ToString();
        }

Write a procedure that will be executed by the event:

//Создаем событие по кнопке.
        private void button2_Click(object sender, EventArgs e)
        {
            handler = new EventHandler(this.do_on_event);
            comboBox1.SelectedIndexChanged += handler;
        }

        //Удаляем событие по кнопке.
        private void button3_Click(object sender, EventArgs e)
        {
            comboBox1.SelectedIndexChanged -= handler;
        }


Now, add two buttons to the form, one to create the event, and the other to delete it:

[[B4]]


Now, when we run the application, we will see that when we select a row in the ComboBox, nothing happens. However, if we click the "Create Event" button, it will start displaying the index position. To cancel the event, we need to click the "Delete Event" button, and when we select a position in the ComboBox, nothing will happen again.

P.S. It should be noted that events can be created multiple times, which means that if we click the "Create Event" button five times, we will create 5 events. To delete them, we will need to click the "Delete Event" button five times.

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.