你调用的对象是空的

Ste*_*Ste 1 .net c# nullreferenceexception

我有这个函数创建运行时文本框:

int i = 0;
private TextBox[] addressBox = new TextBox[100];

private void appendNewTab()
{ 
    addressBox[i] = new TextBox();
    addressBox[i].KeyPress += 
        new KeyPressEventHandler(this.addressBox_KeyPress); 
    i++;
}

void addressBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)13)
    {
        MessageBox.Show(addressBox[i].Text);
    }
}
Run Code Online (Sandbox Code Playgroud)

但我在这里没有将对象引用设置为对象的实例

MessageBox.Show(addressBox[i].Text);
Run Code Online (Sandbox Code Playgroud)

有什么建议吗?

Jon*_*Jon 7

您的问题是,在最新的事件处理程序设置之后TextBox,i会增加指向数组中具有null值的位置(尚未TextBox为其构造).

通常,您可以使用闭包来解决此问题,但在此特定情况下,事件系统会为您TextBox提供在银盘中按下按键的位置:它是sender.

void addressBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)13)
    {
        var textBox = (TextBox) sender;
        MessageBox.Show(textBox.Text);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • +1.可惜,所以很多人盲目地忽略事件处理程序上的发件人参数:( (2认同)