Insert list in listbox

2019-06-14 15:56发布

问题:

I'm new to C# and I'm trying to explore in C#, however I try to add a list in a listbox.

The error that I'm having is : Object reference not set to an instance of an object. Any idea how to resolve this?

namespace WindowsFormsApplication
{
    public partial class Form1 : Form
    {
        something a = something iets();

        public Form1()
        {
            InitializeComponent();
        }
// part1
        class something {

            public List<string> testing { get  ; set; }
        }

// part2
        private void button1_Click(object sender, EventArgs e)
        {
            a.testing.Add("programming");
            a.testing.Add("over");
            a.testing.Add("something");



            foreach (string i in a.testing)
            { listBox1.Items.Add(i); }
        }
    }
}

回答1:

You have to initialize testing at some point before accessing it.

Maybe you could add a constructor to the something class.

public something()
{
  testing = new List<string>();
}

and as pointed in the comments above, replace

something a = something iets();

with this below.

something a = new something(); //this should be the correct thing.


回答2:

I think the reason you're getting a NullReferenceException is that the list of strings in the class something is not initialized. You could define a parameterless constructor and initialize the list there.

public something()
{
    testing = new List<string>();
}

You might also want to know that the first letter of class and property names are usually capitalized (class Something instead of class something, for instance).

Furthermore, you could use the AddRange method instead of adding the strings one by one in a foreach loop.

listbox1.Items.AddRange(a.testing.ToArray());


回答3:

Your class "something" never initializes the List. What you should do is this.

class something{
private List<string> _list;
public something(){
    _list = new List<string>();
}

public List<string> testing {get{return _list;} set{_list = value;}}

}

OR before your line of a.testing.Add() you should do a.testing = new List();