I've always understood that DisplayMember and ValueMember are only supposed to be used when databinding a ComboBox using its DataSource property.
But in some code I'm maintaing I've noticed that using a ComboBox' DisplayMember
property does work without databinding. Setting the property determines what is shown in the combobox. Setting ValueMember
does not seem to work though (it does not set SelectedValue
).
My question is: is it safe to use this behavior? Or is there a risk the behavior may change in upcoming versions of .NET?
I know you'd normally override the ToString
method. In the real code, the MyType class is not as simple as in my example. I'm not sure if it would be safe to override its ToString
method.
A small sample to show this behavior.
using System;
using System.Windows.Forms;
internal class Program {
public class MyType {
public string MyText { get; set; }
public string MyValue { get; set; }
}
public class MyForm : Form {
private readonly ComboBox _myComboBox;
public MyForm() {
_myComboBox = new ComboBox {DisplayMember = "MyText", ValueMember = "MyValue"};
_myComboBox.Items.Add(new MyType {MyText = "First item", MyValue = "1"});
_myComboBox.Items.Add(new MyType {MyText = "Second item", MyValue = "2"});
_myComboBox.SelectedIndexChanged += _myComboBox_SelectedIndexChanged;
Controls.Add(_myComboBox);
}
private void _myComboBox_SelectedIndexChanged(object sender, EventArgs e) {
var cb = (ComboBox) sender;
System.Diagnostics.Debug.WriteLine(
"Index: {0}, SelectedValue: {1}", cb.SelectedIndex, cb.SelectedValue);
}
}
private static void Main() {
Application.Run(new MyForm());
}
}