[英]Object reference not set to an instance of an object
I have this function that create runtime textbox: 我具有创建运行时文本框的以下功能:
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);
}
}
but i have Object reference not set to an instance of an object here 但是我在这里没有将对象引用设置为对象的实例
MessageBox.Show(addressBox[i].Text);
any suggestion? 有什么建议吗?
Your problem is that after setting the event handler on your latest TextBox
, i
is incremented to point to a position in your array that has a null
value (no TextBox
has been constructed for it yet). 您的问题是,在最新的
TextBox
上设置事件处理程序后, i
将递增以指向数组中具有null
值的位置(尚未为其构造TextBox
)。
Generally, you could use a closure to solve this problem, but in this specific case the event system gives you the TextBox
where the key was pressed served in a silver platter: it's sender
. 通常,您可以使用闭包来解决此问题,但是在这种特定情况下,事件系统会为您提供在其中按下了按键的
TextBox
,并以银色拼盘形式提供:它是sender
。
void addressBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
var textBox = (TextBox) sender;
MessageBox.Show(textBox.Text);
}
}
Either addressBox[i] is null or addressBox[i].Text is null. addressBox [i]为null或addressBox [i]。文本为null。 Run it in the debugger to find out.
在调试器中运行它以进行查找。
Well, you are incrementing i after you have created a text box; 好吧,您在创建文本框后将i递增; so, yes, you should get an object reference error.
因此,是的,您应该得到一个对象引用错误。
Consider this. 考虑一下。
You enter the appendNewTab function, i is 0 您输入appendNewTab函数,我是0
The function creates a textbox in the array at addressBox[0] Then you immediately increment i to 1. 该函数在数组中的addressBox [0]处创建一个文本框,然后将i立即增加到1。
When keypress is called it tests addressBox[1]. 调用按键时,它将测试addressBox [1]。 Which is null.
这是空的。
If you have called appendNewTab 100 times, then addressBox[0] through addressBox[99] will have valid textbox controls. 如果您已调用appendNewTab 100次,则addressBox [0]至addressBox [99]将具有有效的文本框控件。 However, i will be set to 100.
但是,我将设置为100。
At which point you should receive an index out of bounds exception when accessing addressBox[i]. 在这一点上,访问addressBox [i]时应该收到索引超出范围的异常。
There are two ways to fix this. 有两种方法可以解决此问题。 The first is to change the keypress code to cast sender to a textbox and use it's text function.
首先是更改按键代码以将发件人转换为文本框并使用其文本功能。 Something like:
就像是:
MessageBox.Show((sender as TextBox).Text);
An optional way, if for some weird reason you want to pop up a message box showing the text of last textbox you created when they pressed enter in any textbox then you can use: 一种可选的方式,如果出于某种奇怪的原因,您想弹出一个消息框,显示在任何文本框中按下回车键时创建的最后一个文本框的文本,则可以使用:
MessageBox.Show(addressBox[i-1].Text);
However, I really don't think that is the behavior you want. 但是,我真的不认为这是您想要的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.