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); }
}
}
}
Your class "something" never initializes the List. What you should do is this.
}
OR before your line of a.testing.Add() you should do a.testing = new List();
I think the reason you're getting a
NullReferenceException
is that the list of strings in the classsomething
is not initialized. You could define a parameterless constructor and initialize the list there.You might also want to know that the first letter of class and property names are usually capitalized (
class Something
instead ofclass something
, for instance).Furthermore, you could use the
AddRange
method instead of adding the strings one by one in a foreach loop.You have to initialize
testing
at some point before accessing it.Maybe you could add a constructor to the something class.
and as pointed in the comments above, replace
with this below.