简体   繁体   English

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

[英]no listbox items after assigning datasource c#

I've been trying for a while to populate a listbox with a datatable. 我一直在尝试用数据表填充列表框。

Here is my code as suggested by almost every page I've seen: 这是我所见过的几乎所有页面所建议的代码:

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

The problem is that there is no items in lb.Items even though lb.datasource.rows has my records I also tried to change the order of assigning datasource with DisplayMember and ValueMember nothing changes 问题是,即使lb.datasource.rows有我的记录, lb.Items也没有项目,我也试图更改使用DisplayMemberValueMember分配datasource的顺序,但没有任何变化

c# winforms C#Winforms

Thanks in advance 提前致谢

Since you are dynamically creating lsitbox you need to add to a control, also set the DataSource later 由于您是动态创建lsitbox的,因此需要添加到控件中,以后还要设置DataSource

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM