Question

So I am still learning as I go and goggling a lot, but I just cannot seem to figure out how to access a method inside a dynamically created User Control.

I managed to get this working:

Control picture = new UserControl1();
picture.Visible = true;
picture.Name = "PIC1";
picture.Location = new Point(0, 0);
picture.Show();
flowLayoutPanel1.Controls.Add(picture);

(UserControl1)picture).SetMSG("Test");

But I want to address each instance of the control by its name like this:

Control picture = new UserControl1();
picture.Visible = true;
picture.Name = "PIC1";
picture.Location = new Point(0, 0);
picture.Show();
flowLayoutPanel1.Controls.Add(picture);

(UserControl1)PIC1).SetMSG("Test");

I think I may just be misunderstanding the entire concept?

Was it helpful?

Solution

You could keep a reference to your dynamically created controls in your view:

class MyView
{
    public void CreateControl(string name)
    {
        Control picture = new UserControl1();
        picture.Visible = true;
        picture.Name = name;
        picture.Location = new Point(0, 0);
        picture.Show();
        flowLayoutPanel1.Controls.Add(picture);

        this.controls.Add(name, picture);
    }

    public void SetMsg(string name, msg)
    {
        ((UserControl1)this.controls[name]).SetMSG(msg);
    }

    private Dictionary<string, Control> controls = new Dictionary<string, Control>();
}

OTHER TIPS

I think I may just be misunderstanding the entire concept?

Yes you are. You can't just use the name of a control like that. You could do:

var PIC1 = flowLayoutPanel1.Controls.Find("PIC1",false);

but you already have a reference to the control (picture) so I don't see the need to get a different reference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top