|
-
December 20th, 2008, 05:20 AM
#1
sender
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
-
December 20th, 2008, 06:42 AM
#2
Re: sender
just put a breakpoint there and find it out ;-)
-
December 20th, 2008, 07:05 AM
#3
Re: sender
sender is object that triggered the event.
for example you can have only one event handler for more than one controls.
consider this example:
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);
}
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.
Last edited by toraj58; December 20th, 2008 at 07:07 AM.
Please rate my post if it was helpful for you.  Java, C#, C++, PHP, ASP.NET
SQL Server, MySQL
DirectX
MATH Touraj Ebrahimi
[toraj_e] [at] [yahoo] [dot] [com]
-
December 20th, 2008, 07:49 PM
#4
Re: sender
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());
}
}
}
-
December 22nd, 2008, 11:19 PM
#5
Re: sender
Another example would be showing what control caused the event to fire.
Code:
Control ctrl = (Control)sender;
MessageBox.Show("We Got Here From: " + ctrl.Name)
NotifyIcon, Button, What Control?
Last edited by ZOverLord; December 22nd, 2008 at 11:40 PM.
-
December 23rd, 2008, 12:22 PM
#6
Re: sender
@ZOverLoard: good example.
Please rate my post if it was helpful for you.  Java, C#, C++, PHP, ASP.NET
SQL Server, MySQL
DirectX
MATH Touraj Ebrahimi
[toraj_e] [at] [yahoo] [dot] [com]
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|