Get information from the sender object

5

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

    
asked by anonymous 31.05.2014 / 04:25

2 answers

4

The sender is of type Object , and has the functionality of when the event is executed, receive the information of such control, for example, if you click on a Button it brings the information of that Button.

Example:

OnaformithastwoButton,onehasinitsTextwithMessage1andMessage2,andButMensagem1hasbeenplacedinits%withthe1numberandtheTagwasplaced2number.Howtorecoverthisinformation:

Code:

RememberthattheButMensagem2eventwillbethesameforbothClick

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 retrieve which Button was clicked and with that retrieves settings, events, and properties. In case the Button property was retrieved and with this the routine makes the decision to show Message 1 or Message 2 , depending on the Button that was triggered. >     

31.05.2014 / 17:59
2

sender must be understood as a wildcard object: the idea that it is not 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 bound to various objects.

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

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

    
31.05.2014 / 04:56