2

我正在开发一个包含 3 个拆分容器(每个两个面板,总共 6 个面板)的 Windows 应用程序。现在我想在每个面板中动态添加 3 个标签。我正在尝试使用 for 循环并访问所有拆分容器及其面板的解决方案,但我不知道如何使用 for 循环来访问拆分容器。我可以为此使用for循环吗?我还想同时向所有面板(6)添加控件。这个怎么做。提前致谢..!!这就是我所做的......

foreach (SplitContainer sp in this.Controls)
        {          
            Label tileTitle = new Label();
            tileTitle.Text = "OneClick";
            tileTitle.Visible = true;
            tileTitle.Location = new Point(10, 10);
            sp.Panel1.Controls.Add(tileTitle);
        }
4

3 回答 3

2
foreach (Control c in this.Controls)
{
    if (c is SplitContainer)
    {
        Label tileTitle = new Label();
        tileTitle.Text = "OneClick";
        tileTitle.Visible = true;
        tileTitle.Location = new Point(10, 10);

        Label tileTitle2 = new Label();
        tileTitle2.Text = "OneClick";
        tileTitle2.Visible = true;
        tileTitle2.Location = new Point(10, 10);

        ((SplitContainer)c).Panel1.Controls.Add(tileTitle);
        ((SplitContainer)c).Panel2.Controls.Add((tileTitle2));
    }
}
于 2012-08-28T15:10:30.297 回答
1

尝试使用 Controls.OfType 扩展只获取 SplitContainer 类型的控件

foreach (SplitContainer sp in this.Controls.OfType<SplitContainer>())
{
    Label title = MakeLabel("OneClick", new Point(10, 10);
    sp.Panel1.Controls.Add(title);
    Label title1 = MakeLabel("OneClick", new Point(10, 10);
    sp.Panel2.Controls.Add(title1);
}

private Label MakeLabel(string caption, Point position)
{
    Label lbl = new Label();   
    lbl.Text = caption;   
    lbl.Location = position;   
    lbl.Visible = true;   
    return lbl;
}

编辑 史蒂夫,您将相同的标签添加到面板 1 和面板 2。我在 panel2 的 add 方法中修复了变量名。

于 2012-08-28T15:41:53.060 回答
0

我以与史蒂夫相同的方式完成此操作,但我使用 a来存储所有拆分容器,因为您可以同时TableLayoutPanel添加多个。 SplitContainerDockstyle.Fill

    private void Form1_Load(object sender, EventArgs e)
    {
        foreach (SplitContainer sc in this.tableLayoutPanel1.Controls.OfType<SplitContainer>())
        {
            Label title = MakeLabel("OneClick", new Point(10, 10));
            sc.Panel1.Controls.Add(title);
            Label title1 = MakeLabel("TwoClick", new Point(10, 10));
            sc.Panel2.Controls.Add(title1);
        }
    }

    private Label MakeLabel(string caption, Point position)
    {
        Label lbl = new Label();
        lbl.Text = caption;
        lbl.Location = position;
        lbl.Visible = true;
        return lbl;
    }

该解决方案完美运行,如下所示:http: //imageshack.us/photo/my-images/838/splitcontainer.png/

于 2012-08-29T08:23:22.263 回答