3D-kreativ
3D-kreativ

Reputation: 9299

Trying to figure out how user control works

I have made a control library and two user controls.

userControl_1 contains a Panel and an ImageList that I have "loaded" with
images in design time.

userControl_2 contains a PictureBox

I have placed userControl_1 on a windows form. The userControl_2 is placed on the panel area in userControl_1.

The goal is to choose a image from the imageList and display it with the pictureBox, something like this:

nameOfPictureBox.Image = nameOfList.Image[number]

But I don't get it to work. I don't understand how to communicate between the user controls? I guess the piece of code above should be inside the userControl_1? But where do I put the code, inside the userControl_1.cs class file or the userControl_1.Designer.cs file?

Preciate some help! Thanks!

Upvotes: 0

Views: 107

Answers (1)

Jay S
Jay S

Reputation: 7994

The designer file is generally only used for web control definitions, and is generated, so should not be the place for your code.

You will want to extend any functionality into the code behind file (.cs) of the user control.

One easy way to expose data from a user control is to create public properties in the code behind of the user control to encapsulate the knowledge of the control but still expose data.

Something like this on the UserControl_2 class:

public Image PictureBoxImage{
    get { return pictureBox.Image; }
    set { pictureBox.Image = value; }
}

You then have an easy property to work with that can hide the inner structure of the control, but still allow your UserControl_1 code behind to set it.

KDiTraglia's code can then be tweaked to do something like:

foreach(var item in this.Panel)
{
    if (item is UserControl_2)
    {
         var ctrl = (UserControl_2)item;
         ctrl.PictureBoxImage = ...
    }
}

This then allows the user control to delegate down to the appropriate inner controls, without UserControl_1 needing to know about that structure.

Upvotes: 2

Related Questions