Maja Okholm
Maja Okholm

Reputation: 3337

C# listBox selectedValue stays null

I have a wpf application with a listbox. I try to access the listbox.selectedValue but it is null, which I dont understand. It even has a default selection so why does it keep being null? ANy clues are greatly appreciated

private void save_Click_1(object sender, RoutedEventArgs e)
{
    string name = foodName.Text;
    string type = preferenceType.SelectedValue.ToString();
    Preference newPreference = new Preference(name, type);
    string temp = name + ";" + type;
    newPreference.save(temp, newPreference.path);
    MessageBox.Show($"{name} {type} saved");
}

And the xaml:

<TextBox x:Name="foodName" TextWrapping="Wrap" Text="Food name" GotFocus="foodName_GotFocus" HorizontalScrollBarVisibility="Auto" Grid.ColumnSpan="3" Margin="1.4,50,10.2,280" Grid.Column="1"/>
<ListBox x:Name="preferenceType" Grid.ColumnSpan="3" Margin="1.4,81,10.2,246" Grid.Column="1">
    <ListBoxItem Selected="ListBoxItem_Selected">allergy</ListBoxItem>
    <ListBoxItem Selected="ListBoxItem_Selected">hate</ListBoxItem>
    <ListBoxItem Selected="ListBoxItem_Selected">dislike</ListBoxItem>
</ListBox>
<Button x:Name="savePreference" Content="Save" HorizontalAlignment="Left" Margin="1.4,115,0,0" VerticalAlignment="Top" Width="78" Click="save_Click_1" Grid.ColumnSpan="3" Grid.Column="1" Height="19"/>

Upvotes: 2

Views: 367

Answers (1)

Dark Templar
Dark Templar

Reputation: 1155

try this code:

        ListBoxItem testitem = preferenceType.SelectedValue as ListBoxItem;
        string name = foodName.Text;
        string type = testitem.Content.ToString();
        Preference newPreference = new Preference(name, type);
        string temp = name + ";" + type;
        newPreference.save(temp, newPreference.path);
        MessageBox.Show(name + type + "saved");

Upvotes: 1

Related Questions