Can you clarif what is sender object declard in almost all predefined function protutype ?
Example,
private void Btn_click(object sender, EventArgs e)
I don't know what I can do with sender
THANKs so much
Printable View
Can you clarif what is sender object declard in almost all predefined function protutype ?
Example,
private void Btn_click(object sender, EventArgs e)
I don't know what I can do with sender
THANKs so much
just put a breakpoint there and find it out ;-)
sender is object that triggered the event.
for example you can have only one event handler for more than one controls.
consider this example:
Explanation: before running the above code add two button control to your main form and let the name properties of them be : button1 and button2.Code:private void Form1_Load(object sender, EventArgs e)
{
button1.Click += new EventHandler(Btn_click);
button2.Click += new EventHandler(Btn_click);
}
private void Btn_click(object sender, EventArgs e)
{
Button btn = (Button)sender;
MessageBox.Show(btn.Text);
}
then in form load event i attached single event handler function (Btn_click) to both of their click events.
if button1 trigger the event MessageBox will show its text property that is button1; if button2 trigger it MessageBox will show text property of second button.
Notice that sender is type of Object so i casted it to Button to extract the text property.
Just like Toraj said, it is the 'sender' of the event. If you were to create your own event and model it after the way they are done it .NET, it would look something like this:
Code:class EventTest
{
public event EventHandler TestEvent;
protected virtual void OnTestEvent(EventArgs e)
{
// test for null in case there are no listeners
if (TestEvent != null)
{
// pass in 'this' as the sender object
TestEvent(this, e);
}
}
private int _someValue;
public int SomeValue
{
set
{
_someValue = value;
OnTestEvent(new EventArgs());
}
}
}
Another example would be showing what control caused the event to fire.
NotifyIcon, Button, What Control?Code:Control ctrl = (Control)sender;
MessageBox.Show("We Got Here From: " + ctrl.Name)
@ZOverLoard: good example.