57

Can anyone tell me how to get the selected item of a ComboBox to a string variable?

string selected = cmbbox.SelectedItem.ToString();
MessageBox.Show(selected);

This gives me System.Data.DataRowView in my MessageBox

Roshan
  • 2,983
  • 7
  • 37
  • 53

4 Answers4

96

Try this:

string selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
MessageBox.Show(selected);
Leo Chapiro
  • 13,405
  • 7
  • 56
  • 87
  • 5
    Is there a reason to prefer this over `this.ComboBox.Text`? – Mike E Jan 08 '15 at 18:35
  • 6
    @Mike E: Yes, there is a reason. ComboBox.Text gets or sets the text associated with this control (has nothing in common with selected item): http://msdn.microsoft.com/de-de/library/system.windows.forms.combobox.text%28v=vs.110%29.aspx – Leo Chapiro Jan 08 '15 at 19:08
  • 1
    @LeoChapiro Regarding the `ComboBox.Text` property, according to Microsoft documentation it says: "The string of the currently selected item." – Simple May 06 '21 at 19:36
  • 2
    @Simple Microsoft documentation is unfortunately Microsoft documentation, i.e. frequently wrong and misleading. You put this in a SelectionChanged callback and SelectedIndex and SelectedItem will reflect the change. Text will not. – Paul Childs Jul 14 '21 at 03:25
13

You can use as below:

string selected = cmbbox.Text;
MessageBox.Show(selected);
Omer
  • 5,464
  • 12
  • 58
  • 73
9

Test this

  var selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
  MessageBox.Show(selected);
Community
  • 1
  • 1
-3
SelectedText = this.combobox.SelectionBoxItem.ToString();
Undo
  • 25,381
  • 37
  • 106
  • 126