Reputation: 47
I am using WinForms. I have number of TextBoxes created at runtime on FlowLayoutPanel. I want to set Text property for each TextBox from an Array
I write this code
to create TextBoxes in runtime
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);
}
I get an Exception here: Object reference not set to an instance of an object
for (int i = 1; i <= Hlk_WidthArray.Length; i++)
{
Hlk_WidthArray[i] += Hlk_WidthArray[i];
flowLayoutPanel1.Controls["txtwidth" + i].Text = Hlk_WidthArray[i].ToString();
}
Upvotes: 0
Views: 124
Reputation: 139
You forgot add the TextBox to Panel, here is the example:
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;
}
Some changes in your code:
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
}
Upvotes: 1
Reputation: 2945
You are not adding TextBox to the 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();
}
Upvotes: 1
Reputation: 6079
You need to add the Textbox controls to Groupbox, Just like your adding the Groupbox control to 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);
}
Upvotes: 0