我有動態增加的一類應該工作時控制的麻煩是這樣的:動態添加類控制
當一個新加入它應該出現在下面的左側面板工具條。 到目前爲止,我有麻煩讓他們出現(中間的一個只是我做的設計)。
下面是代碼:
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;
}
}
出現的問題就在這裏:
Additional information: Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.
//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的構造函數:
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;
}
EquationBox的構造函數是什麼樣的? –
你的意思是? '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; }' –
嘗試'用戶控制':右鍵單擊您的項目,選擇添加...,用戶控件...,命名用戶控件並單擊確定。將TextBox,CheckBox等拖放到用戶控件上。現在你可以實例化它並將它添加到表單中。 –