I have a PictureBox on my user control and I have added lots of this User Control on my form. Thing is whenever a user clicks on PictureBox he should get that User Control item to which this PictureBox belongs.
So, on my User Control I have added this code
public usercontrol1()
{
InitializeComponent();
pictureBox1.Parent = this;
}
Then on my Form
private void form1_Load(object sender, EventArgs e)
{
var c = new usercontrol1();
c.pictureBox1.Click += item_click;
c = new usercontrol1();
c.pictureBox1.Click += item_click;
}
private void item_click(object sender, EventArgs e)
{
usercontrol1 abc = pictureBox1.Parent; // Giving Error
}
I tried this approach to set user control as parent control of picturebox and tried to retrieve it from picturebox click event on form. But resulting in failure. How do I get the usercontrol1 object from PictureBox click event?
I'm sure the error message (you forgot to tell us) pretty clearly tells you what is wrong: pictureBox1.Parent
is of type Control
and therefor cannot be assigned directly to variable of type usercontrol1
.
You have to cast it to usercontrol1
:
usercontrol1 abc = (usercontrol1)pictureBox1.Parent;
Note that this will throw an InvalidCastException
if for any reason Parent
is some other Control
than a usercontrol1
. So you better use the as
operator:
private void item_click(object sender, EventArgs e)
{
usercontrol1 abc = pictureBox1.Parent as usercontrol1;
if (abc == null) return; // as returns null if the cast fails
// do something with abc
}
or use the enhanced (pattern matching) is
operator in C#7:
private void item_click(object sender, EventArgs e)
{
if (!pictureBox1.Parent is usercontrol1 abc) return;
// do something with abc
}