简体   繁体   English

C#Winforms将ListBox绑定到DataTable问题

[英]C# Winforms Bind ListBox to DataTable Issue

Well, I've ran into a problem when binding ListBox control to DataTable. 好吧,我在将ListBox控件绑定到DataTable时遇到了问题。

Code: 码:

using (DbWrapper db = DbFactory.GetConnection("SQLite").WrapIn<MyDbWrapper>())
{
    db.Open();

    DataTable results = db.ExecuteQuery("SELECT id,title FROM schedule");

    ScheduleList.DataSource = results;
    ScheduleList.DisplayMember = "title";
    ScheduleList.ValueMember = "id";
}

This code is supposed to receive data from my SQLite database, and bind it to my ScheduleList, but when I compile I see my ListBox filled with System.Data.DataRowView strings. 这段代码应该从我的SQLite数据库接收数据,并将它绑定到我的ScheduleList,但是当我编译时,我看到我的ListBox填充了System.Data.DataRowView字符串。

在此输入图像描述

There's no problems with database. 数据库没有问题。 The application is receiving data, and the data is correct. 应用程序正在接收数据,数据是正确的。 If I iterate through my datatable I will get id and title as column names, so theres nothing wrong with them. 如果我遍历我的数据表,我会得到id和title作为列名,所以它们没有错。

I've read that the problem may be solved by changing binding order or setting ListBox.Sorted property to false. 我已经读过可以通过更改绑定顺序或将ListBox.Sorted属性设置为false来解决问题。 I've tried it all and still no success. 我已经尝试了所有这些但仍然没有成功。

Any suggestions? 有什么建议? Are there any other solutions except iterating over datarows and adding them manually? 除了遍历数据行并手动添加它们之外,还有其他解决方案吗?

Best Regards. 最好的祝福。

I used this code and it worked. 我使用这个代码,它工作。

DataTable oTable = new DataTable();
oTable.Columns.Add("ID", typeof(int));
oTable.Columns.Add("TITLE", typeof(string));

DataRow oNewRow = null;
for (int i = 0; i < 10; i++) 
{
    oNewRow = oTable.NewRow();

    oNewRow["ID"] = i;
    oNewRow["TITLE"] = "Title_" + i.ToString();

    oTable.Rows.Add(oNewRow);
}

listBox1.DataSource = oTable;
listBox1.ValueMember = "ID";
listBox1.DisplayMember = "TITLE";

在此输入图像描述

EDIT: you may need to give tha datasource first and then declare the value-display members. 编辑:您可能需要先提供数据源,然后声明值显示成员。

Rearrange the statements: 重新排列声明:

ScheduleList.DisplayMember = "title";
ScheduleList.ValueMember = "id";
ScheduleList.DataSource = results;

My bad. 我的错。 The ListBox wasn't reacting to DisplayMember and ValueMember changes because of inappropriate code in custom ListBox DrawItem event. 由于自定义ListBox DrawItem事件中的代码不合适,ListBox没有对DisplayMember和ValueMember更改做出反应。

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

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