3

Well, I've ran into a problem when binding ListBox control to 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.

enter image description here

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.

I've read that the problem may be solved by changing binding order or setting ListBox.Sorted property to 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.

2
  • Possible duplicate of: stackoverflow.com/questions/8803859/… Commented May 30, 2013 at 13:39
  • Well, it is, but solutions posted there didn't solve my problem. Commented May 30, 2013 at 13:41

3 Answers 3

4

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

enter image description here

EDIT: you may need to give tha datasource first and then declare the value-display members.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your effort, but I've already fixed the problem. It was caused by custom DrawItem event.
0

Rearrange the statements:

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

Comments

0

My bad. The ListBox wasn't reacting to DisplayMember and ValueMember changes because of inappropriate code in custom ListBox DrawItem event.

1 Comment

I suspected something like that because my testing, and indeed every search result I found, suggested the code you had ought be working well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.