James Kennedy
James Kennedy

Reputation: 21

Listbox, not getting selected item

I have an WPF form with a listbox and a button on it.

I populate a listbox (tagbox) with the List and then bind this with datasource as below.

private void WeekFood_Load(object sender, EventArgs e)
        {
         List<string> tags = new List<string>() { "A", "B", "C"};
         tagbox.DataSource = tags;
         InitializeComponent();
        }

Then when I click the button, I run the following code

 private void GenSunday_Click(object sender, EventArgs e)
        {
            MessageBox.Show(tagbox.SelectedItems.Count.ToString());            
        }

No matter how many items are selected in the listbox it always returns 0 with tagbox.SelectedItems always being null.

I have tried populating the box by iterating the list with valuemember and displaymember however this also does not fix things.

How is this fixable.

Many thanks in advance

Upvotes: 2

Views: 402

Answers (1)

Ambareesh
Ambareesh

Reputation: 81

In WPF, please use ItemSource property for ListBox and bind the object to it.

Also call the InitializeComponent(); before assigning any data to the controls.

//MainWindow.xaml.cs

        public MainWindow()
        {
            InitializeComponent();

            List<string> tags = new List<string>() { "A", "B", "C" };
            tagBox.ItemsSource = tags;
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(tagBox.SelectedItems.Count.ToString());
        }

In MainWindow.xaml


<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <ListBox x:Name="tagBox" HorizontalAlignment="Left" Height="100" Margin="99,249,0,0" VerticalAlignment="Top" Width="561"/>
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="99,57,0,0" VerticalAlignment="Top" Width="148" Height="34" Click="button_Click"/>

    </Grid>
</Window>


Upvotes: 1

Related Questions