将列表框添加到动态创建的tabpages中

时间:2014-08-02 07:34:24

标签: c# .net

我正在尝试以编程方式将列表框添加到tabcontrols中动态创建的tabpages中。我不明白问题在哪里,因为它在编译时没有给我任何错误。我在if语句if (c is TabPage)上使用了断点,它正确显示了创建的标签页。

    public void createControls()
    {
        TabControl tabcontrol = new TabControl();
        panel1.Controls.Add(tabcontrol);
        tabcontrol.Dock = DockStyle.Fill;
        int n = 1;
        do
        {
            tabcontrol.Controls.Add(new TabPage() { Name = "Property #" + n + "", Text = "Property #" + n + "" });
            n++;
        } while (n == pnum);

        foreach (Control c in panel1.Controls)
        {
            if (c is TabPage)
            {
                ListBox list = new ListBox();
                list.Items.AddRange(new object[] {
                "Id",
                "Name",
                "Entity"});
                list.Location = new System.Drawing.Point(20, 38);
                list.Name = "listBox1";
                list.ScrollAlwaysVisible = true;
                list.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
                list.Size = new System.Drawing.Size(134, 147);
                c.Controls.Add(list);
            }
        }

    }

1 个答案:

答案 0 :(得分:0)

您需要确保访问 immediate 容器的控件。

foreach (Control c in panel1.Controls)

应该是

foreach (Control c in tabcontrol.Controls)