Ste
Ste

Reputation: 1520

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?

Upvotes: 1

Views: 2058

Answers (3)

ChrisLively
ChrisLively

Reputation: 88044

Well, you are incrementing i after you have created a text box; so, yes, you should get an object reference error.

Consider this.

You enter the appendNewTab function, i is 0
The function creates a textbox in the array at addressBox[0] Then you immediately increment i to 1.

When keypress is called it tests addressBox[1]. Which is null.


If you have called appendNewTab 100 times, then addressBox[0] through addressBox[99] will have valid textbox controls. However, i will be set to 100.

At which point you should receive an index out of bounds exception when accessing 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.

Upvotes: 0

Jon
Jon

Reputation: 437326

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).

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.

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

Upvotes: 7

dthorpe
dthorpe

Reputation: 36072

Either addressBox[i] is null or addressBox[i].Text is null. Run it in the debugger to find out.

Upvotes: 0

Related Questions