Birol Capa
Birol Capa

Reputation: 369

User Control c# Add Dynamically

I create a user control dynamically in my code

UserControl myobject = new UserControl();

myObject contains a button etc. when I add this control to my picturebox

picturebox.Controls.Add(myobject);

my picturebox's backgorund image is dissappeared.

Why?

note: the button can be seen however. I want picturebox to be seen also

Upvotes: 2

Views: 19583

Answers (3)

Uthistran Selvaraj
Uthistran Selvaraj

Reputation: 1371

Try this:

UserControl myobject = new UserControl();
Button but = new Button();
but.BackColor = Color.Gray
pic.BackColor = Color.Green;
myobject.Controls.Add(but);
pic.Visible = true;
pic.Controls.Add(myobject);

Upvotes: 2

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

Set transparent basckground color of your user control. This will make picturebox visible:

UserControlDisplay myobject = new UserControlDisplay();
myobject.BackColor = Color.Transparent;
picturebox.Controls.Add(myobject);

BTW I believe you have different name of user control. And yes, as @samjudson stated, PictureBox should not be used this way: try to use Panel with background image instead (approach will stay same - use transparent color to see parent control):

panel.BackgroundImage = // your image
UserControlDisplay myobject = new UserControlDisplay();
myobject.BackColor = Color.Transparent;
panel.Controls.Add(myobject);

Upvotes: 5

samjudson
samjudson

Reputation: 56853

The PictureBox control is not meant to be used as a container. Try adding a parent Panel or similar and the adding the PictureBox and your custom control to the Panel control.

Upvotes: 1

Related Questions