Object reference not set to an instance of an object when filling listbox

2.2k views Asked by At
private void FillListBox()
{
    string ConctingString = "Data Source=AHMED_S_MASHALY;Initial Catalog=BookLibrary;Integrated Security=True";
    string CommandString = "SELECT * FROM BookLibraryTable2";

    SqlConnection Conncting = new SqlConnection(ConctingString);

    Conncting.Open();

    SqlCommand CMD = new SqlCommand(CommandString, Conncting);

    SqlDataReader DR1 = CMD.ExecuteReader();

    while (DR1.Read())
    {
        string listboxvalues = DR1.GetString(1);
        listBox1.Items.Add(listboxvalues);
    }
}

this is the error

An unhandled exception of type 'System.NullReferenceException' occurred in BookLibrary.exe

Additional information: Object reference not set to an instance of an object.

the error appear at this line >>>>>> listBox1.Items.Add(listboxvalues); <<<<<<

1

There are 1 answers

0
David Arno On

The error is occurring because either listBox1 or listBox1.items is null. The easiest way to find out which is to add a breakpoint at that line and examine their values.