I created some TextBox and Labels dynamic the program with the following code.
public void DynamicObjects(int countRow)
{
tableLayout.RowCount = countRow;
tableLayout.ColumnCount = 2;
for (int i = 0; i < countRow; i++)
{
Label lblTitle = new Label();
lblTitle.Text = i + "box";
lblTitle.TextAlign = ContentAlignment.MiddleCenter;
tableLayout.Controls.Add(lblTitle, 0, i);
TextBox txtValue = new TextBox();
txtValue.Text = "2";
txtValue.Name = "txt_numberSabad" + i+1;
tableLayout.Controls.Add(txtValue, 1, i);
}
}
Now I want to set the value inside the program somewhere and I used the following code.
private void Form_load(object sender, EventArgs e)
{
DynamicObjects(5);
TextBox txt = (TextBox)(tableLayout.Controls["txt_numberSabad"+3]);
txt.Text = "new text for texBox";
}
But I get the following error.
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Firstly, I’d personally suggest that you store your textboxes in a list or something so you don’t have to access them by name.
But beyond that, I strongly suspect that the problem is that the control that you expect to have the name “txt_numberSabad3” actually has the name “txt_numberSabad21”. Here’s a short program to show why:
int i = 2;
string name1 = "txt_numberSabad" + i+1;
Console.WriteLine(name1);
string name2 = "txt_numberSabad" + (i + 1);
Console.WriteLine(name2);
The output is:
txt_numberSabad21
txt_numberSabad3
In this expression: "txt_numberSabad" + i+1
the precedence rules mean it’s equivalent to ("txt_numberSabad" + i) + 1
. To get the result you actually want, you need to evaluate i + 1
and then append that to the string:
txtValue.Name = "txt_numberSabad" + (i + 1);