简体   繁体   中英

List in class is null even though I made an instance of the class

I'm trying to access the list personal from some functions in the main program but I keep getting that it's not an instance of...

The class code:

[Serializable()]
class FaktNr
{
    public int lopnummer;
    public int year;

    public List<string> personal = new List<string>();

    public FaktNr()
    {
        personal = new List<string>();

    }
}

The form code:

public partial class Form1 : Form
{

    internal FaktNr faktNr = new FaktNr(); 

    public Form1()
    {
        InitializeComponent();
    }

    private void laggTillPerson_Click(object sender, EventArgs e)
    {
            faktNr.personal.Add(ComboBox1.Text);
    }

Code is shortened here but it shows the essentials. Nullreferenceexception occurs in function laggTillPerson_Click .

I want to add that its not the ComboBox that is the problem since i already tried this: faktNr.personal.Add("uhiouh");

You are getting the exception on ComboBox1.Text , your ComboBox1 could be null, not your list personal , Try replacing your code with:

faktNr.personal.Add("test string");

and see if you still get the exception.

You are accessing the Text property of the Combobox, instead you may use ComboBox.SelectedText Property

Or you can check for null in your event:

private void laggTillPerson_Click(object sender, EventArgs e)
{
     if(ComboBox1 != null)
          faktNr.personal.Add(ComboBox1.Text);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM