Insert list in listbox

大兔子大兔子 提交于 2019-12-08 15:05:31

问题


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();



来源:https://stackoverflow.com/questions/15370663/insert-list-in-listbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!