我的问题是,我无法将值写入文本框对象。 以下是创建文本框的代码部分:
int number = 10;
TextBox[,] arrayTextBoxenHochpunkte= new TextBox[10,3];
for(int i=0; i<number; i++)
{
TextBox newTextBox = new TextBox();
newTextBox.Location = new Point(0, (3+(i * 25)));
newTextBox.Size = new Size(25, 26);
newTextBox.Text = "H" + Convert.ToString(i + 1);
newTextBox.ReadOnly = true;
panel1.Controls.Add(newTextBox);
arrayTextBoxenHochpunkte[i, 0] = newTextBox;
TextBox newTextBox2 = new TextBox();
newTextBox2.Location = new Point(28, (3+(i * 25)));
newTextBox2.Size = new Size(50, 26);
newTextBox2.ReadOnly = true;
panel1.Controls.Add(newTextBox2);
arrayTextBoxenHochpunkte[i, 1] = newTextBox2;
TextBox newTextBox3 = new TextBox();
newTextBox3.Location = new Point(83, (3+(i * 25)));
newTextBox3.Size = new Size(50, 26);
newTextBox3.ReadOnly = true;
panel1.Controls.Add(newTextBox3);
arrayTextBoxenHochpunkte[i, 2] = newTextBox3;
}
以下是应在文本框中写入值的方法:
private void addHochpunkt(float xValue, float yValue)
{
int i;
for (i = 0; i < 10; i++)
{
if (!(string.IsNullOrWhiteSpace(arrayTextBoxenHochpunkte[i,1].Text)))
{
continue;
}
arrayTextBoxenHochpunkte[i, 1].Text = "xValue";
arrayTextBoxenHochpunkte[i, 2].Text = "yValue";
}
}
我做错了什么?
答案 0 :(得分:0)
如果您已全局声明数组TextBox[,] arrayTextBoxenHochpunkte
,那么您不会在本地再次声明具有相同名称的数组。以这种方式初始化本地的一个,当你尝试使用全局的那个时,留下全局空触发着名的NullReferenceException
public class Form1 : Form
{
private TextBox[,] arrayTextBoxenHochpunkte;
public void SomeMethod()
{
int number = 10;
// This line declares an array with the same name and thus
// hides the global one declared at the form/class level
// All your initialization goes into this local one that is
// lost when you exit from this method..... remove it...
// TextBox[,] arrayTextBoxenHochpunkte= new TextBox[10,3];
// This line initializes the global array so it is available
// also in other methods.....
arrayTextBoxenHochpunkte= new TextBox[10,3];
.....
initialization code
.....
}
private void addHochpunkt(float xValue, float yValue)
{
int i;
for (i = 0; i < 10; i++)
{
// Here you try to reference the global array, but
// your current code leaves the global one without initialization
// thus a NullReferenceException.....
if (!(string.IsNullOrWhiteSpace(arrayTextBoxenHochpunkte[i,1].Text)))
{
continue;
}
// I suppose that you want to write the value
// of the two variables not their names.
arrayTextBoxenHochpunkte[i, 1].Text = xValue.ToString();
arrayTextBoxenHochpunkte[i, 2].Text = yValue.ToString();
}
}
}