Convert.ToString occurs an NRE

148 views Asked by At

http://turcguide.com/stack/nre1.jpg

When I use and user defined object such in my exemple mytext[i].text i get an NullReferenceException but if i use a design time object there is no NullReferenceException

In my exemple, the line below does not give an exception but if i put an arrayed object such mytext[i].text(run time object) instead of IngNbrTxt.Text(desing time object) I get an exception as show in the link above.

string myvar = Convert.ToString(IngNbrTxt.Text);

private void inglist_click(object sender, EventArgs e)
{
    TextBox[] mytext = new TextBox[9];
    int rows = 0;
    Int32.TryParse(IngNbrTxt.Text, out rows);

    if (inglist.SelectedIndex > -1 && this.CommandFrame.Visible == true)
    {
        for (int i = 0; i < rows; ++i)
        {
            //string myvar = (mytext[i].Text != null ? mytext[i].Text.ToString() : (string)null); 
            string myvar = Convert.ToString(IngNbrTxt.Text);
            if (myvar == null)
            {
                mytext[i].Text = Convert.ToString(inglist.Items[inglist.SelectedIndex]);
            }
        }
    }
    else
    {
        return;
    }
}
1

There are 1 answers

1
Damith On BEST ANSWER

as @BartoszKP commented mytext[i] is null and you will get an exception when you set Text property of null object , try with below

 if (myvar == null)
 {
     mytext[i] = new TextBox();
     mytext[i].Text = Convert.ToString(inglist.Items[inglist.SelectedIndex]);
 }

OR

TextBox[] mytext =Enumerable.Range(0,8).Select(x=> new TextBox()).ToArray();