Single post

WinForms ComboBox with values like the WebForms DropDownList

Want to have values for each ComboBox item in WinForms? Here is a simple way of doing so. Add a class in your project named ComboBoxItem:

public class ComboBoxItem
{
  private string _value;
  private string _text;

  public string Value { get { return _value; } }
  public string Text  { get { return _text ; } }

  public ComboBoxItem (string cValue, cText)
  {
    this._value = cValue;
    this._text  = cText;
  }
}

Now when adding items to the ComboBox, you would do this:

ComboBox myBox = new ComboBox ();
myBox.Items.Add (new ComboBoxItem ("1", "January"));
myBox.Items.Add (new ComboBoxItem ("2", "February"));

myBox.DisplayMember = "Text"; // Specifies what to display
this.Controls.Add (myBox);

To retrieve the current selected value and text, you could do:

string SelectedItemValue = (myBox.SelectedItem as ComboBoxItem).Value;
string SelectedItemText  = (myBox.SelectedItem as ComboBoxItem).Text;

January 19th, 2008 at 4:17 pm

If you’re using .NET 2.0 you can try this:

comboBox1.ValueMember = “Key”;
comboBox1.DisplayMember = “Value”;

comboBox1.Items.Add(new KeyValuePair(0, “zero”));
comboBox1.Items.Add(new KeyValuePair(1, “one”));

if using .NET 1.x i think there’s another class you could use (without the generics)… but can’t remember exactly.

January 19th, 2008 at 4:18 pm

new KeyValuePair<int, string>(0, “zero”) that is !

NahuelGQ
March 9th, 2008 at 7:29 pm

Hi guys:
Another way to get the same behaviour is to overriding the “ToString” method.

Like this:

public class ComboBoxItem
{
private string _value;
private string _text;

public string Value { get { return _value; } }
public string Text { get { return _text ; } }

public ComboBoxItem (string cValue, cText)
{
this._value = cValue;
this._text = cText;
}

public override string ToString()
{
return this.Text;
}
}

NahuelGQ

LEAVE A COMMENT

theme by teslathemes