views:

1272

answers:

6

There are two pictureboxes with two different images.

If I click on one picture box, the image in it should be cleared.

To make the matters worse, both of the picture boxes have only one common event handler. How can I know which picturebox generated the event? I would appreciate source code in Visual C++.net

I need to know what to write inside the function:

private: System::Void sqaure_Click(System::Object^  sender, System::EventArgs^  e) {

}

EDIT: The problem is that when I try to cast sender to picurebox, it gives an error saying that the types cannot be converted.

A: 

You can use the sender object. Cast it to a picture box control and compare it with the two available picture boxes.

My Visual C++ is a little bit rusty and can't provide code now.

kgiannakakis
A: 

kgiannakakis, The problem is that when I try to cast sender to picurebox, it gives an error saying that the types cannot be converted.

Niyaz
Could you provide the code you are using?
kgiannakakis
PictureBox p = (PictureBox)sender;
Niyaz
Try: PictureBox^ p = (PictureBox ^)sender;
Roger Lipscombe
A: 

Are you sure the sender object actually is the type you assume it to be?

Nailer
+3  A: 

How are you doing the cast? In most cases like this I would use:

PictureBox ^pb = safe_cast<PictureBox^>(sender);
if(pb != null) {
    // logic goes here
}

(Note that I've corrected the above code after Josh pointed out my reference flaw. Thanks!)

the dynamic cast will give you the right object type if it can cast, or null if it cant (it's the equiv. of "as" in C#)

If this does give you a null reference, then perhaps your sender is not what you think it is?

Toji
A: 

If you're trying the code that Toji gave, then there's you're problem - try this:

PictureBox ^pb = safe_cast<PictureBox^>(sender);

Unlike C#, where you don't need any syntax to denote managed heap objects, C++\CLI differentiates between stack objects (PictureBox pb), pointers to heap objects (PictureBox *pb), and handles to managed heap objects (PictureBox ^pb). The three are not the same thing, and have different lifetimes and usages.

Eclipse
Ah, yes. Thanks for the correction. (Been a little bit since I've done C++\CLI).
Toji
A: 

How are you trying to cast? I'd generally use dynamic_cast or safe_cast:

PictureBox ^ pb = dynamic_cast<PictureBox^>(sender);
if (pb != nullptr)
{
...
}

or

try
{
    PictureBox ^ pb = safe_cast<PictureBox^>(sender);
    ...
}
catch(InvalidCastException ^ exp)
{
    // Handle a cast that went awry
}

It should be pretty straight-forward from there...

shash