简体   繁体   中英

C#.NET ComboBox control

I have an application working on hand held device with .NET compact framework, using C#.NET. The problem I am facing is ComboBox control is behaving very un-cenrtain, sometimes it shows the contents but some times it just shows System.DataRow kind of string in ComboBox. Although it shows this System.DataRow string but it still has its values. I have a selectedIndexChanged event on combobox and it returns right value even UI is showing System.DataRow as display.

Thanks in advance. Cheers.

In the code that loads your ComboBox, you probably have something that looks like this:

foreach (DataRow row in YourDataTable.Rows)
{
    YourComboBox.Items.Add(row);
}

You're basically loading each entire DataRow into your ComboBox, and the ComboBox is using the DataRow's default ToString() value, which is "System.Data.DataRow". You need to instead load your ComboxBox with one of the DataRow's fields , like this:

foreach (DataRow row in YourDataTable.Rows)
{
    YourComboBox.Items.Add(row["column1"].ToString());
}

Update : You may have a typo in your DisplayMember property. This code:

DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Rows.Add(1, "Bob");
dt.Rows.Add(2, "Doug");
dt.Rows.Add(3, "Beth");
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "Name";
comboBox1.DataSource = dt;

works correctly, as expected, but DisplayMember is case-sensitive, so if I change the second-to-last line to:

comboBox1.DisplayMember = "name";

all the items in the ComboBox say "System.Data.DataRowView". I think you just need to check your column names.

Thanks for your help. I figured out the problem. So the scenario was to populate a combo box with the values from database. Database query was returning me three columns ID, Name, Size. But I needed only 2 columns Name and ID for combobox. I was getting values from database and then adding a new row on client side into that datatable before populating into combobox. In this client side row I was adding only 2 columns Name and ID but not the size. And this thing was stuffing everything. Its wierd but it works fine now. I think I will do some more testing and see if that error arises again.

Thanks for the help anyways.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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