hellodave
hellodave

Reputation: 41

Selecting ListBox item returns null

I'm populating my list using data binding in WPF and everything is working fine. But I can't get the string of the selected item in my ListBox.

Here's my code of the button where I'm trying to get the value of selected Item.

private void hexButton_Click(object sender, RoutedEventArgs e)
    {
        if (imeiListBox.SelectedIndex == -1)
        {
            MessageBox.Show("Select IMEi from IMEI List!");
        }
        else
        {
            ListBoxItem myselectedItem= imeiListBox.SelectedItem as ListBoxItem;
            string text = myselectedItem.ToString();
        }
    }

And here's my XAML code of the ListBox.

 <ListBox x:Name="imeiListBox" 
          ItemsSource="{Binding Path=Devices}"  
          HorizontalAlignment="Left"  
          SelectionChanged="imeiListBox_SelectionChanged" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=Imei}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>

The problem is that string text = myselectedItem.ToString(); is returning null. How does one resolve that?

Upvotes: 1

Views: 717

Answers (2)

mm8
mm8

Reputation: 169390

SelectedItem doesn't return a ListBoxItem. It returns an instance of the type (Device ?) where the Imei property is defined.

So you should cast to this type:

var myselectedItem= imeiListBox.SelectedItem as Device;
if (myselectedItem != null)
    string text = myselectedItem.Imei.ToString();

Or you could use the dynamic keyword:

dynamic myselectedItem= imeiListBox.SelectedItem;
string text = myselectedItem.Imei?.ToString();

Note that this will fail at runtime if SelectedItem returns anything else than an object with an Imei property. If you know the type, casting is preferable.

Upvotes: 2

Corentin Pane
Corentin Pane

Reputation: 4943

The imeiListBox.SelectedItem will be an object with the same type as the items you put in the ItemsSource of your ListBox, probably a Device object looking at your code.

You have to cast it like

imeiListBox.SelectedItem as Device;

instead.

Upvotes: 3

Related Questions