noob question: how do i access the object sender properties

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

based on the following code generated by the IDE:
private void toolStripButton1_Click(object sender, EventArgs e) {}

How do I convert sender to a ToolStripButton object so I can access its
properties?
 
You will need to type cast the object:

private void toolStripButton1_Click(object sender, EventArgs e)
{
ToolStripButton tsb = (ToolStringButton)sender;
}

However, my guess is that toolStripButton1 is a member variable that you
could use directly and you could ignore the sender property altogether.
 
First check to make sure that sender is the correct type. Then once
you have verified that, you can cast it and access its properties.

private void toolStripButton1_Click(object sender, EventArgs e)
{
if(sender is ToolStripButton)
{
ToolStripButton t = sender as ToolStripButton;
//Work with properties of t to get what you need
}
}
 
AAMOI, is there any difference between:

ToolStripButton t = sender as ToolStripButton;

and

ToolStripButton t = (ToolStripButton)sender;

Seems that the second example is used a lot more frequently e.g. on MSDN etc
than the first...
 
ToolStripButton t = sender as ToolStripButton;
Sets t to null if sender is not a ToolStripButton;
ToolStripButton t = (ToolStripButton)sender;
Throws an exception if sender is not a ToolStripButton;

The second style is probably more common among ex-C/C++ programmer (which,
particularly in the early days, included most of MSFT's C# team), because
C/C++ doesn't have the "as" keyword.
--
--
Truth,
James Curran
[erstwhile VC++ MVP]

Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com
 
Mark Rae said:
AAMOI, is there any difference between:

ToolStripButton t = sender as ToolStripButton;

and

ToolStripButton t = (ToolStripButton)sender;

Seems that the second example is used a lot more frequently e.g. on MSDN etc
than the first...

The latter throws an exception immediately if sender is neither null
nor a reference to an instance of ToolStipButton (or a descendent). (If
sender were declared to be a type which had a conversion to
ToolStripButton, it would also invoke that conversion).

The first *just* says "If sender is a reference to an instance of
ToolStripButton or a descendant, set t to the same value; otherwise set
t to null".

If you need to test first, it's cheaper to use the first form, as you
only end up casting internally once, so instead of:

if (sender is ToolStripButton)
{
ToolStripButton t = (ToolStripButton)sender;
...
}

you'd have:

ToolStripButton t = sender as ToolStripButton:
if (t != null)
{
....
}

If, however, it's a bug for sender to be anything other than a
ToolStripButton, I'd just cast.
 
Back
Top