-1

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?

  • 1
    If the PictureBox is in the UserControl, then its parent is already the UserControl. Your code created new UserControls, but didn't add them to the form. I suspect you want to do something like this: [How do I make an Event in the Usercontrol and have it handled in the Main Form?](https://stackoverflow.com/q/7880850/719186) – LarsTech Apr 13 '18 at 15:09
  • the last two lines in Load are redundant. b) the uc c is never added to a controls collection. c) in the item_click you should cast the sender to picturebox (or control); then you can access its Parent. – TaW Apr 13 '18 at 15:31
  • Sorry i forgot to type it here but there I have added – Kaustubh Patange Apr 13 '18 at 17:28

1 Answers1

0

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
}
René Vogt
  • 43,056
  • 14
  • 77
  • 99