Reputation: 81
I bind my combobox from entityframework and when I try to get value from my combobox by selecting value it gives back text like this {NameOfCompany = Name } How can i get only the value Name?
Thats the code in xaml
<ComboBox SelectionChanged="ComboFirma_SelectionChanged" Name="ComboFirma" Margin="109,10,10,0" Height="28" VerticalAlignment="Top">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Name="txbCombo" Text="{Binding NameOfCompany}"></TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
And I bind it like this.
var query2 = from f in model.Firmas
select new
{
f.NameOfCompany
};
ComboFirma.ItemsSource = query2.ToList();
I tried something like this to gets the selected value but always i get an exception.
var str = (TextBox)ComboFirma.Template.FindName("txbCombo", ComboFirma);
lblCompanyNameShow.Content = str.SelectedText;
Upvotes: 0
Views: 1176
Reputation: 33364
ComboBox.SelectedItem
will be of a item type. So normally you would need to cast SelectedItem
to type of item in your collection. Now, because, in your case it's anonymous type, it's more difficult I think easiest way to get NameOfCompany
is to use dynamic
dynamic selectedItem = ComboFirma.SelectedItem;
var name = selectedItem.NameOfCompany;
or you can use SelectedValue
/SelectedValuePath
<ComboBox Name="ComboFirma" ... SelectedValuePath="NameOfCompany">
and in code
var name = (string)ComboFirma.SelectedValue;
Upvotes: 1
Reputation: 2104
Try like this
TextBlock tb1 = (TextBlock)ComboFirma.SelectedItem;
lblCompanyNameShow.Content = str.SelectedText;
Upvotes: 0