kr13
kr13

Reputation: 537

Getting Text from ComboBox in WPF

I have a ComboBox in WPF and I cant access its selected item text.

I have tried

cbItem.Text;
cbItem.SelectedItem.ToString();

XAML:

<ComboBox Name="cbItem" SelectedValuePath="ITEM_ID">
     <ComboBox.ItemTemplate>
          <DataTemplate>
               <TextBlock Text="{Binding ITEM_NAME}" />
          </DataTemplate>
     </ComboBox.ItemTemplate>
</ComboBox>

Upvotes: 0

Views: 1133

Answers (3)

BlackRabbit
BlackRabbit

Reputation: 78

Do ITEM_ID and ITEM_NAME come from an object?

String textComboBox = ((ITEMCLASS)cbItem.SelectedItem).ITEM_NAME.ToString();

Upvotes: 1

Ajay
Ajay

Reputation: 6590

Try this

<ComboBox Name="cbItem" SelectedValuePath="ITEM_ID">
 <ComboBox.ItemTemplate>
      <DataTemplate>
           <TextBlock Name="txtblck" Text="{Binding ITEM_NAME}" />
      </DataTemplate>
 </ComboBox.ItemTemplate>

TextBox str = (TextBox)cbItem.FindName("txtblck");

string text = str.Text;

Upvotes: 0

Microsoft DN
Microsoft DN

Reputation: 10030

Try

 cbItem.SelectedValue.ToString()

This will work only if combobox values are same as the combobox text

EDIT:

Solution 1

You have to get access to the ComboBox's TextBox:

var str = (TextBox)cbItem.Template.FindName("PART_EditableTextBox", cbItem);

Then you can access the SelectedText property of that TextBox:

var selectedText = str.SelectedText; // This will give you text of selected item

Solution 2

ComboBoxItem typeItem = (ComboBoxItem)cbItem.SelectedItem;

string value = typeItem.Content.ToString();// This will give you text of selected item

Upvotes: 0

Related Questions