动态添加控件类

时间:2015-09-21 01:18:35

标签: c# winforms

我在动态添加一类控件时遇到了麻烦,这些控件应该在工作时看起来像这样:

enter image description here

添加新的时,它应显示在工具条下的左侧面板中。 到目前为止,我无法让它们出现(中间的那个只是我制作的设计)。

enter image description here

以下是代码:

// beautiful code, well close enough
function myFunction() {
    var i, arr, blah;
    var iteratorFunction = function(item) {   
        //... code ...
    }
    //... 50 lines of code ...
    for(i = 0; i < 100; i++) {  // the var token has been removed
        //... code ...
    }
    //... more code ...
    for(i = 0; i < 100; i++){  //  the var token has been removed
        //... code ...
    }

    blah = {};                    // var token removed
    arr = [blah, blah, blah];     // var token removed
    // function lofted
    arr.forEach(iteratorFunction);
}

问题出现在这里:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        //Problem Occurs Here
        EquationBox[] EquationBoxArray = new EquationBox[12];
        for (int x = 0; x < 12; x++)
        {
            EquationBoxArray[x] = new EquationBox();
            ActiveForm.Controls.Add(EquationBoxArray[x].mainPanel);
            ActiveForm.Controls.Add(EquationBoxArray[x].colorPanel);
        }
    }

    private void add_line_Click(object sender, EventArgs e) //Add Line
    {

    }

    private void clear_Click(object sender, EventArgs e) //Clear Lines
    {

    }
}

public class EquationBox
{        
    public Panel colorPanel = new Panel();
    public Panel mainPanel = new Panel();
    public TextBox equationBox = new TextBox();
    public CheckBox isVisibleBox = new CheckBox();

    public EquationBox()
    {
        mainPanel.Size = new Size(200, 72);
        colorPanel.Size = new Size(33, 72);
        mainPanel.Location = new Point(50, 50);
        colorPanel.Location = new Point(50, 50);

        colorPanel.BackColor = Color.Red;
    }
}

当我运行它时,它返回:

//Problem Occurs Here EquationBox[] EquationBoxArray = new EquationBox[12]; for (int x = 0; x < 12; x++) { EquationBoxArray[x] = new EquationBox(); ActiveForm.Controls.Add(EquationBoxArray[x].mainPanel); ActiveForm.Controls.Add(EquationBoxArray[x].colorPanel); }

即使在开始发生之前,EqautionBox也不会出现。

先谢谢,这真让我烦恼。

对于EquationBox的构造函数:

Additional information: Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.

2 个答案:

答案 0 :(得分:2)

首先,你的控件出现了,但是mainPanel是重叠的colorPanel,你看不到mainPanel(与你的表格颜色相同的BG颜色),所以首先解决了添加的交换

EquationBox[] EquationBoxArray = new EquationBox[12];
for (int x = 0; x < 12; x++)
{
    EquationBoxArray[x] = new EquationBox();
    this.Controls.Add(EquationBoxArray[x].colorPanel);
    this.Controls.Add(EquationBoxArray[x].mainPanel);
}

我正在使用this.Controls,不确定ActiveForm.Controls部分,可能在构建时,您的Form1不是活动的,因此发生了错误。

Ps:我建议将colorPanel添加到mainPanel,并仅将mainPanel添加到Form。正如Steve Wellens所说,UserControl是一个很好的解决方案。

答案 1 :(得分:1)

EquationBox存在各种问题,TextBox和CheckBox不在面板中。将其设为UserControl会更容易。

然后使用FlowLayoutPanel.

进行定位