Grab information from object Sender

Asked

Viewed 6,164 times

5

How does the search for information through the Nder object work and in what situations can I use it, with what types of events? This is to avoid event redundancy. Where can I explore these possibilities? For example : multiple buttons from 0 to 9. And generate a single event for all.

2 answers

5


The sender is the type Object, and has the functionality when the event runs, receive information from such control, for example if you click on a Button he brings the information of this Button.

Example:

inserir a descrição da imagem aqui

In one form has two Button, a has on your Text with Message 1 and Message 2 respecitvamente the ButMensagem1 was placed on your property Tag the number 1 and in the ButMensagem2 the number was placed 2. How to recover this information:

Code:

Obs: Remembering that the event Click will be the same for both Button

private void ButMensagem_Click(object sender, EventArgs e)
{
    //Button butMensagem = (Button)sender;
    //ou 
    Button butMensagem = sender as Button; 
    switch (((string)butMensagem.Tag))
    {
        case "1": // mensagem 1
            {
                MessageBox.Show("Botão Clicado: Mensagem 1", "Clicado", MessageBoxButtons.OK, MessageBoxIcon.Information);
                break;
            }
        case "2": // mensagem 2
            {
                MessageBox.Show("Botão Clicado: Mensagem 2", "Clicado", MessageBoxButtons.OK, MessageBoxIcon.Information);
                break;
            }
    }

}

That is, using a Cast you recover which Button was clicked and retrieves the settings, events and properties. In case the property was recovered Tag and with it the routine makes the decision to show the Message 1 or Message 2, depending on the Button that was triggered.

3

The sender should be understood as a joking object: the idea of it not being typed is precisely so that it can be manipulated by events in which the object types are different, and that a single event can be linked to several objects.

In this answer, how to write a single event that manipulates several PictureBoxes. Note that the solution suggests converting the sender for a type to perform manipulation of some property or implement some business rule (for the case of the question, manipulate the visibility when the object is checked).

Your example already responds well to one of the advantages of using the sender, how to work the values of several buttons. The limit of possibilities is precisely the amount of properties that the object has. After the casting, you can read and manipulate the property you want (since the property is not read-only).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.