填充列表框时,对象引用未设置为对象的实例

时间:2013-12-09 20:02:48

标签: c# listboxitems

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

这是错误

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

其他信息:Object reference not set to an instance of an object.

错误出现在此行>>>>>> listBox1.Items.Add(listboxvalues); <<<<<<

1 个答案:

答案 0 :(得分:1)

发生错误是因为listBox1或listBox1.items为null。找出哪个是在该行添加断点并检查其值的最简单方法。