Reputation: 469
Whenever I'm trying to get text from combo box it extracts data like System.Windows.Controls.ComboBoxItem: Abc
How can I get only "Abc" ? I mean to say only value not entire stack trace. my code seems like:-
XAML:-
<StackPanel Orientation="Horizontal" Width="auto" HorizontalAlignment="Center" Margin="0,10,0,0">
<TextBlock HorizontalAlignment="Left" FontFamily="/Vegomart;component/Images/#My type of font" Text="User Type:- " FontSize="18" Foreground="Black"/>
<ComboBox x:Name="userType" HorizontalAlignment="Right" FontFamily="/Vegomart;component/Images/#My type of font" Width="170" FontSize="18" Foreground="Black" Margin="40,0,0,0" >
<ComboBoxItem> Abc</ComboBoxItem>
</ComboBox>
</StackPanel>
C#:-
string value = userType.SelectedItem.ToString();
System.Diagnostics.Debug.WriteLine(value);
Your effort will be appreciated :).
Thanks,
Upvotes: 1
Views: 2793
Reputation: 184516
<ComboBoxItem> Abc</ComboBoxItem>
sets the Content
to Abc
, so you would need to cast your SelectedItem
to ComboBoxItem
and get that property.
(That the XAML sets the content can be seem in the base class ContentControl
which has a ContentPropertyAttribute
that defines which property to set.)
Upvotes: 1
Reputation: 781
<ComboBox x:Name="userType" SelectionChanged="userType_SelectionChanged">
<ComboBoxItem Content="Abc"/>
<ComboBoxItem>Bcd</ComboBoxItem>
</ComboBox>
Then in code behind:
private void userType_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var comboBox = sender as ComboBox;
if (comboBox != null)
{
var comboBoxItem = comboBox.SelectedItem as ComboBoxItem;
if (comboBoxItem != null)
{
var content = comboBoxItem.Content;
System.Diagnostics.Debug.WriteLine(content);
}
}
}
Upvotes: 3
Reputation: 738
You can get the content of the item:
ComboBoxItem item = (ComboBoxItem)userType.SelectedItem;
string value = (string)item.Content;
System.Diagnostics.Debug.WriteLine(value);
Upvotes: 1
Reputation: 186
This should return the text of the selected item in the ComboBox.
string value = userType.Text.ToString();
Upvotes: 1