C# 在动态创建的用户控件中访问方法?

C# 在动态创建的用户控件中访问方法?,c#,visual-c#-express-2010,C#,Visual C# Express 2010,因此,我仍在边走边学习,并一直盯着它看,但我似乎不知道如何在动态创建的用户控件中访问方法 我设法让它工作: Control picture = new UserControl1(); picture.Visible = true; picture.Name = "PIC1"; picture.Location = new Point(0, 0); picture.Show(); flowLayoutPanel1.Controls.Add(picture); (UserControl1)pict

因此,我仍在边走边学习,并一直盯着它看,但我似乎不知道如何在动态创建的用户控件中访问方法

我设法让它工作:

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");
但我想通过名称来处理控件的每个实例,如下所示:

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");
我想我可能只是误解了整个概念

我想我可能只是误解了整个概念

是的,你是。不能只使用这样一个控件的名称。你可以做:


但是您已经有了对控件的引用(
picture
),因此我认为没有必要获取其他引用。

您可以在视图中保留对动态创建的控件的引用:

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>();
}
类MyView
{
公共void CreateControl(字符串名称)
{
控件图片=新的UserControl1();
图片可见=真实;
picture.Name=名称;
图片位置=新点(0,0);
picture.Show();
flowLayoutPanel1.控件.添加(图片);
此.controls.Add(名称、图片);
}
public void SetMsg(字符串名称,msg)
{
((UserControl1)this.controls[name]).SetMSG(msg);
}
私有字典控件=新字典();
}

是的,你几乎是误会了。为什么C#会知道
PIC1
是某个对象的名称?你能做到这一点:
usercontrol1pic1=newusercontrol1()?是否必须使用
控制图片
?然后你就可以引用这个控件了。我想让每个控件都有一个动态引用,但对于这个问题来说是简化的。类似于int i=1;i++;控件图片+i=新用户控件();这当然是额外的工作,只有在视图中集中访问控件时才有好处。考虑D斯坦利的方法,因为它更简单。我认为我的误解是在生成控制开始时,我不会结束多个控件引用为(图片),所以一个改变会改变它们吗?你只能有一个代码>图片< /C>变量,并且变量只能指向一个东西-所以没有,您不会更改多个项目。但我必须看更多的代码才能更好地理解如何生成多个控件。因此,如果我想在它们生成后对它们进行处理,我将无法动态生成。我需要一个用于picture1、2、3等的代码块,或者干脆不用麻烦,在designer中以单个代码块的形式完成所有工作objects@user3464024现在还不清楚你想做什么。是的,您可以动态生成它们,或者重复使用
picture
或者使用不同的变量名。但是,不能使用控件的
Name
作为变量来动态引用控件。
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>();
}