分配数据源c#后没有列表框项

时间:2016-12-07 17:47:09

标签: c# winforms datatable listbox datasource

我一直试图用数据表填充列表框。

以下是我见过的几乎每个页面所建议的代码:

ListBox lb = new ListBox();

using (SqlCommand cmd = new SqlCommand("SELECT * FROM Files", con))
{
    SqlDataAdapter dap = new SqlDataAdapter(cmd);
    DataTable tblShapes = new DataTable();
    dap.Fill(tblShapes);

    lb.DataSource = tblShapes;

    // define Display and Value members
    lb.DisplayMember = "Name";
    lb.ValueMember = "Id";
}

问题是lb.Items中没有项目,即使lb.datasource.rows有我的记录 我还尝试更改datasource分配DisplayMemberValueMember无变化的顺序

c#winforms

提前致谢

1 个答案:

答案 0 :(得分:3)

由于您是动态创建lsitbox,因此需要添加到控件中,以后再设置DataSource

ListBox lb = new ListBox();
this.Controls.Add(lb);
lb.DisplayMember = "Name";
lb.ValueMember = "Id";
lb.DataSource = tblShapes;