ComboBox not showing text
I have the following code that I'm trying to use to populate a ComboBox, but it's not showing the actual text of the objects that I'm adding.
internal partial class SortBox : UserControl {
private Field[] FieldReferences
...
internal Field[] Fields {
...
set {
this.FieldReferences = value;
this.cboFields.Items.Clea开发者_如何学Gor();
string NoneString = "(none)";
this.cboFields.Items.Add(NoneString);
this.cboFields.SelectedItem = NoneString;
foreach (Field Field in this.FieldReferences) {
MessageBox.Show(Field.ToString()); // <- This displays what I want displayed perfectly.
this.cboFields.Items.Add(Field);
}
}
}
...
}
public partial class Field : UserControl {
protected string LabelValue;
...
public override string ToString() {
return this.LabelValue;
}
}
Here's what I'm getting; they're all blank:
What am I doing wrong?
EDIT: Apparently, my Field class is inheriting from UserControl. I've done some tests, and it apparently has something to do with the fact that the class inherits from System.ComponentModel.Component.
If I am reading your code right, you are trying to put a usercontrol inside a combobox.
Overriding the ToString won't work when you do that, so to make the code that you currently have work, just change the DrawMode:
This works:
cboFields.DrawMode = DrawMode.OwnerDrawFixed;
cboFields.DrawItem += new DrawItemEventHandler(cboFields_DrawItem);
private void cboFields_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
if (e.Index > -1)
e.Graphics.DrawString(cboFields.Items[e.Index].ToString(), e.Font, Brushes.Black, e.Bounds);
}
But I have to say, I don't know if putting a UserControl inside a ComboBox collection is the best way to do this. I would seriously consider refactoring that differently.
The items you add to the combo box should also be strings, just like in your message box.
Try: this.cboFields.Items.Add(Field.ToString());
Alternately, you can try setting the DisplayMember field, although ToString should already be the default:
this.cboFields.DisplayMember = "ToString()"
精彩评论