1

When running my code i put several string on different lines of the textbox but it breaks saying there is a Null Exception Error on "Items.Add(item)" I am not sure why I am getting this error because in visual studio the string in the variable item is not null it contains a return character through so I am not sure if that is an issue.. for example item = "uno\r". Also, Items is a list of strings. Does anyone know why I keep getting this Null Exception?

    public List<string> Items;        


    public void getItemsFromTextBox(TextBox textbox)
    {
        string[] lines = textbox.Text.Split('\n');
        foreach (string item in lines)
        {
            if (!String.IsNullOrWhiteSpace(item))
                Items.Add(item);
        }
    }
1
  • 1
    The Items collection is uninitialized. Commented Oct 5, 2013 at 6:36

5 Answers 5

6

You have not initialized your list, it's null! Add

public List<String> Items = new List<String>();
Sign up to request clarification or add additional context in comments.

Comments

1

You must create instance of Items list:

public void getItemsFromTextBox(TextBox textbox)
{
    Items = new List<string>();
    string[] lines = textbox.Text.Split('\n');
    foreach (string item in lines)
    {
        if (!String.IsNullOrWhiteSpace(item))
            Items.Add(item);
    }
}

Comments

1

Just try with following code.I guess your Items list is global one and shared list .so better to check that List is initialize or if not then initialize first and do the rest of the thing.

    public List<string> Items;        

    public void getItemsFromTextBox(TextBox textbox)
    {
        if(null == Items)
        {
          Items = new List<string>();
        }
        foreach (string item in textbox.Text.Split('\n'))
        {
            if (!String.IsNullOrWhiteSpace(item))
                Items.Add(item);
        }
    }

Comments

1

You must have create an instance of List Items.

use

public List<String> Items = new List<String>();

or use the below code

public void getItemsFromTextBox(TextBox textbox)
{
    List<string> Items = !string.IsNullOrWhiteSpace(textbox.Text) ? textbox.Text.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList() : new List<string>();
}

Comments

0

Make sure that you have instantiated "Items".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.