Type Cast "Object"

G

Guest

I am writing a click event for an array of PictureBoxes:

for (int i = 0; i < 10; i++)
pic.Click += new EventHandler (pic_Click);
private void pic_Click (object sender, System.EventArgs e)

In the event handler, I want to type cast the "sender" to a PictureBox, so I
can do ((PictureBox) sender).Location to change its location rather than
using a loop to compare the sender with each PictureBox in the array.

How to do this in C#?

Thank you in advance.

Eric
 
A

Andrew Kirillov

Hello

You can do it as you wrote: ((PictureBox) sender).Location.
But, you should do it only if you are sure, that sender is an instance of
PictureBox.
You can do the next way:
if (sender is PictureBox)
{
((PictureBox) sender).Location ....
}
 
M

Michael S

or like this:

PictureBox pb = sender as PictureBox;
if (pb != null)
{
pb.Location.....
}

Happy Coding
- Michael S

Andrew Kirillov said:
Hello

You can do it as you wrote: ((PictureBox) sender).Location.
But, you should do it only if you are sure, that sender is an instance of
PictureBox.
You can do the next way:
if (sender is PictureBox)
{
((PictureBox) sender).Location ....
}

--
With best regards,
Andrew

http://www.codeproject.com/script/profile/whos_who.asp?id=1181072


Won Won said:
I am writing a click event for an array of PictureBoxes:

for (int i = 0; i < 10; i++)
pic.Click += new EventHandler (pic_Click);
private void pic_Click (object sender, System.EventArgs e)

In the event handler, I want to type cast the "sender" to a PictureBox,
so I
can do ((PictureBox) sender).Location to change its location rather than
using a loop to compare the sender with each PictureBox in the array.

How to do this in C#?

Thank you in advance.

Eric

 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top