Jack Nelson
Jack Nelson

Reputation: 83

How do I run a function on code generated UserControl?

I have created a form that has generated several UserControls. There has to be an unlimited amount that can be added - there wont necessarily, but there needs to not be a cap on the amount.

I have used the following code to add them:

for (int i = 0; i < ucCount; i++)
{
    UserControl1 uc = new UserControl1();
    uc.name = "uc" + i.ToString();
    flowLayout.Controls.Add(uc);
    uc.Click -= new EventHandler(uc_Click);
    uc.Click += new EventHandler(uc_Click);
}

ucCount is simply a variable to change the amount that are added.

The problem I'm having now, is I have a method in the UserControls that needs to be run when a button is pressed. This is the code for the following method:

public void ResizeTrucks()
{
    ...
}

Normally, if I had added the controls with a special name, I would have done the following:

uc.ResizeTrucks();

Since I added them in the code, and changed their names, I can no longer do that.

I now have the following code to change the size of all the usercontrols.

foreach (Control c in flowTrucks.Controls)
{
    c.Width = 103;
    c.Height = 528;
}

Basically, the problem that I'm facing is running a function in a usercontrol that I have generated in code, so I can't just do uc1.ResizeTrucks();.

I think I remember reading somewhere that you can get the function by name and then run it, but I haven't been able to find it anywhere. Any help will be appreciated.

Upvotes: 0

Views: 28

Answers (1)

Mark Brackett
Mark Brackett

Reputation: 85665

You want to cast to the appropriate user control type, and then you can run the function. Something like:

foreach (Control c in flowTrucks.Controls)
{
    c.Width = 103;
    c.Height = 528;

    var x = c as UserControl1;
    if (x == null) continue; // not a UserControl1
    x.ResizeTrucks();
}

Upvotes: 1

Related Questions