Click to See Complete Forum and Search --> : sender
Vancel
December 20th, 2008, 04:20 AM
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
MNovy
December 20th, 2008, 05:42 AM
just put a breakpoint there and find it out ;-)
toraj58
December 20th, 2008, 06:05 AM
sender is object that triggered the event.
for example you can have only one event handler for more than one controls.
consider this example:
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);
}
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.
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.
BigEd781
December 20th, 2008, 06:49 PM
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:
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());
}
}
}
ZOverLord
December 22nd, 2008, 10:19 PM
Another example would be showing what control caused the event to fire.
Control ctrl = (Control)sender;
MessageBox.Show("We Got Here From: " + ctrl.Name)
NotifyIcon, Button, What Control?
toraj58
December 23rd, 2008, 11:22 AM
@ZOverLoard: good example.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.