开发者

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

My WPF ComboBox contains only text entries. The user will select one. What is the simplest way to get the text of the selected ComboBoxItem? Please answer in both C# and Visual Basic. Here is my ComboBox:

<ComboBox Name="cboPickOne">
    <ComboBoxItem>This</ComboBoxItem>
    <ComboBoxItem>should be</ComboBoxItem>
开发者_高级运维    <ComboBoxItem>easier!</ComboBoxItem>
</ComboBox>

By the way, I know the answer but it wasn't easy to find. I thought I'd post the question to help others. REVISION: I've learned a better answer. By adding SelectedValuePath="Content" as a ComboBox attribute I no longer need the ugly casting code. See Andy's answer below.


In your xml add SelectedValuePath="Content"

<ComboBox 
  Name="cboPickOne"
  SelectedValuePath="Content"
  >
  <ComboBoxItem>This</ComboBoxItem>
  <ComboBoxItem>should be</ComboBoxItem>
  <ComboBoxItem>easier!</ComboBoxItem>
</ComboBox>

This way when you use .SelectedValue.ToString() in the C# code it will just get the string value without all the extra junk:

   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!


I just did this.

string SelectedItem = MyComboBox.Text;


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();


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜