我正在使用WinForms。我在FlowLayoutPanel上运行时创建了多个TextBox。我想从数组
为每个TextBox设置Text属性我写这段代码
在运行时创建TextBoxes
for (int i = 1; i <= no_gb; i++)
{
GroupBox g1 = new GroupBox();
g1.Text = "Window " + i;
g1.Size = new Size(207, 105);
TextBox txt = new TextBox();
txt.Name = "txtwidth" + i;
flowLayoutPanel1.Controls.Add(g1);
}
我在这里得到一个异常:对象引用没有设置为对象的实例
for (int i = 1; i <= Hlk_WidthArray.Length; i++)
{
Hlk_WidthArray[i] += Hlk_WidthArray[i];
flowLayoutPanel1.Controls["txtwidth" + i].Text = Hlk_WidthArray[i].ToString();
}
答案 0 :(得分:1)
您没有将TextBox添加到FlowLayoutPanel。
for (int i = 1; i <= no_gb; i++)
{
GroupBox g1 = new GroupBox();
g1.Text = "Window " + i;
g1.Size = new Size(207, 105);
g1.Name = "gbG1";
TextBox txt = new TextBox();
txt.Name = "txtwidth" + i;
g1.Controls.add(txt);
flowLayoutPanel1.Controls.Add(g1);
}
for (int i = 1; i <= Hlk_WidthArray.Length; i++)
{
Hlk_WidthArray[i] += Hlk_WidthArray[i];
((TextBox)(((GroupBox)flowLayoutPanel1.Controls["gbG1"]).Controls["txtwidth" + i])).Text = Hlk_WidthArray[i].ToString();
}
答案 1 :(得分:1)
您忘了将TextBox添加到Panel,这是示例:
Panel panel1 = new Panel();
panel1.Dock = System.Windows.Forms.DockStyle.Fill;
panel1.Location = new System.Drawing.Point(0, 0);
panel1.Name = "panel1";
panel1.Size = new System.Drawing.Size(789, 424);
panel1.TabIndex = 0;
this.Controls.Add(panel1);
for (int i = 0; i < 20; i++)
{
TextBox Box = new TextBox();
Box.Location = new System.Drawing.Point(55, 12+(20*i));
Box.Name = "Box"+i.ToString();
Box.Size = new System.Drawing.Size(100, 20);
panel1.Controls.Add(Box);
}
for (int i = 0; i < 20; i++)
{
panel1.Controls["Box" + i].Text = "TextBox " + i;
}
代码中的一些更改:
for (int i = 1; i <= no_gb; i++)
{
GroupBox g1 = new GroupBox();
g1.Text = "Window " + i;
g1.Size = new Size(207, 105);
g1.Name = "GB" + i.ToString(); //New Line
TextBox txt = new TextBox();
txt.Name = "txtwidth" + i;
g1.Controls.Add(txt); //New Line
flowLayoutPanel1.Controls.Add(g1);
}
for (int i = 1; i <= Hlk_WidthArray.Length; i++)
{
Hlk_WidthArray[i] += Hlk_WidthArray[i];
flowLayoutPanel1.Controls["GB" + i].Controls["txtwidth" + i].Text = Hlk_WidthArray[i].ToString(); //Edited Line
}
答案 2 :(得分:0)
您需要将文本框控件添加到Groupbox,就像将Groupbox控件添加到flowLayoutPanel1
一样for (int i = 1; i <= no_gb; i++)
{
GroupBox g1 = new GroupBox();
g1.Text = "Window " + i;
g1.Size = new Size(207, 105);
TextBox txt = new TextBox();
txt.Name = "txtwidth" + i;
g1.Controls.Add(txt);//New Line (Code added)
flowLayoutPanel1.Controls.Add(g1);
}