What is the simplest way to get the selected text in a combo box containing only text entries?

烂漫一生 提交于 2019-12-02 23:35:56
<ComboBox 
  Name="cboPickOne"
  SelectedValuePath="Content"
  >
  <ComboBoxItem>This</ComboBoxItem>
  <ComboBoxItem>should be</ComboBoxItem>
  <ComboBoxItem>easier!</ComboBoxItem>
</ComboBox>

In code:

   stringValue = cboPickOne.SelectedValue.ToString()

Just to clarify Heinzi and Jim Brissom's answers here is the code in Visual Basic:

Dim text As String = DirectCast(cboPickOne.SelectedItem, ComboBoxItem).Content.ToString()

and C#:

string text = ((ComboBoxItem)cboPickOne.SelectedItem).Content.ToString();

Thanks!

If you already know the content of your ComboBoxItem are only going to be strings, just access the content as string:

string text = ((ComboBoxItem)cboPickOne.SelectedItem).Content.ToString();

I just did this.

string SelectedItem = MyComboBox.Text;
Mahmoud

If you add items in ComboBox as

youComboBox.Items.Add("Data"); 

Then use this:

youComboBox.SelectedItem; 

But if you add items by data binding, use this:

DataRowView vrow = (DataRowView)youComboBox.SelectedItem;
DataRow row = vrow.Row;
MessageBox.Show(row[1].ToString());

Using cboPickOne.Text should give you the string.

var s = (string)((ComboBoxItem)cboPickOne.SelectedItem).Content;

Dim s = DirectCast(DirectCast(cboPickOne.SelectedItem, ComboBoxItem).Content, String)

Since we know that the content is a string, I prefer a cast over a ToString() method call.

Nitin Tyagi

Use the DataRowView.Row.Item[Index] or ItemArray[Index] property to get the SelectedItem, where Index is the index of the column in the DataTable used as itemSource for the combobox. In your case it will be 0. Instead of index you can also pass the Column name also:

VB:

Dim sItem As String=DirectCast(cboPickOne.SelectedItem, DataRowView).Row.Item(1).ToString()

C#

String sItem=((DataRowView)cboPickOne.SelectedItem).Row.Item[1].ToString();

To get the SelectedValue you can use:

VB:

Dim sValue As String=cboPickOne.SelectedValue.ToString()

C#

String sValue=cboPickOne.SelectedValue.ToString();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!