문제

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;
    }
}
도움이 되었습니까?

해결책

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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top