-2

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;
    }
}
Marc
  • 3,905
  • 4
  • 21
  • 37
Ismail Gunes
  • 548
  • 1
  • 9
  • 24

1 Answers1

1

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();
Damith
  • 62,401
  • 13
  • 102
  • 153
  • 1
    Do you realize that `Enumerable.Repeat(new TextBox(), 9).ToArray()` will create nine distinct references to ***one*** `TextBox` instance. That is hardly useful. – Jeppe Stig Nielsen Sep 14 '13 at 19:39