问题
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.
回答1:
<ComboBox
Name="cboPickOne"
SelectedValuePath="Content"
>
<ComboBoxItem>This</ComboBoxItem>
<ComboBoxItem>should be</ComboBoxItem>
<ComboBoxItem>easier!</ComboBoxItem>
</ComboBox>
In code:
stringValue = cboPickOne.SelectedValue.ToString()
回答2:
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!
回答3:
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();
回答4:
I just did this.
string SelectedItem = MyComboBox.Text;
回答5:
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());
回答6:
Using cboPickOne.Text
should give you the string.
回答7:
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.
回答8:
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();
来源:https://stackoverflow.com/questions/3721430/what-is-the-simplest-way-to-get-the-selected-text-in-a-combo-box-containing-only