locked
get all selected items from wpf checkbox list give me error RRS feed

  • Question

  • I have listbox with checked box as following, & it binding its data from sql server database,
    , I want to get selected items value When I run this but I got this error
     
    Unable to cast object of type 'System.Data.DataRowView' to type 'System.Windows.Controls.CheckBox'.

    <Window.Resources>
            <DataTemplate x:Key="NameColumnTemplate">
                <CheckBox Height="20"  FontFamily="Arial" FontSize="14"  Content="{Binding Path=PermissionDescription}" 
                          Tag="{Binding PermissionID}" HorizontalAlignment="Stretch" VerticalAlignment="Center"
                          />
            </DataTemplate>
        </Window.Resources>
    <Grid>
    <ListBox HorizontalAlignment="Stretch" Margin="12,12,136,21" Name="lstEmployees" 
                              VerticalAlignment="Stretch" ItemsSource="{Binding Tables[0]}"  
                              ItemTemplate="{StaticResource NameColumnTemplate}" 
                              ScrollViewer.VerticalScrollBarVisibility="Auto" removed="{x:Null}" 
                             BorderBrush="#FFAD7F30"  
                     SelectionChanged="lst_SelectionChanged" CheckBox.Click="lst_SelectionChanged"/>
    <Button Content="listbox" Height="23" HorizontalAlignment="Left" Margin="214,207,0,0" Name="btnShowSelectedItems" 
                    VerticalAlignment="Top" Width="75" Click="btnShowSelectedItems_Click" />
    </Grid>
    
    public Window2()
            {
                InitializeComponent();
                // bind data 
                lstEmployees.DataContext = SelJobsCat();
            }
     
     private void btnShowSelectedItems_Click(object sender, RoutedEventArgs e)
            {
                foreach (CheckBox item in lstEmployees.Items)
                {
                    if (item.IsChecked == true)
                    {
                        System.Windows.MessageBox.Show((item.Content + " is checked."));
     
                    }
                }
            }
     
            private void lst_SelectionChanged(object sender, RoutedEventArgs e)
            {
                if (e.OriginalSource is CheckBox)
                {
                    lstEmployees.SelectedItem = e.OriginalSource;
                }
     
                if (lstEmployees.SelectedItem == null) return;
                Console.WriteLine(lstEmployees.SelectedIndex);
                Console.WriteLine(((CheckBox)lstEmployees.SelectedItem).IsChecked);
            }
    where is my error please, Thanks

    Saturday, June 29, 2013 3:23 PM

Answers

  • <Window x:Class="WpfApplication1.Window1"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Window1" Height="300" Width="300">
        <Window.Resources>
            <DataTemplate x:Key="NameColumnTemplate">
                <CheckBox Height="20"  FontFamily="Arial" FontSize="14"  Content="{Binding Path=PermissionDescription}" 
                          Tag="{Binding PermissionID}" IsChecked="{Binding IsSelected, Mode=TwoWay}" HorizontalAlignment="Stretch" VerticalAlignment="Center"
                          />
            </DataTemplate>
        </Window.Resources>
        <Grid>
            <ListBox HorizontalAlignment="Stretch" Margin="12,12,136,21" Name="lstEmployees" 
                              VerticalAlignment="Stretch" ItemsSource="{Binding Tables[0]}"  
                              ItemTemplate="{StaticResource NameColumnTemplate}" 
                              ScrollViewer.VerticalScrollBarVisibility="Auto" 
                             BorderBrush="#FFAD7F30"  
                     SelectionChanged="lst_SelectionChanged" CheckBox.Click="lst_SelectionChanged"/>
            <Button Content="listbox" Height="23" HorizontalAlignment="Left" Margin="214,207,0,0" Name="btnShowSelectedItems" 
                    VerticalAlignment="Top" Width="75" Click="btnShowSelectedItems_Click" />
        </Grid>
    </Window>
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;
    
    namespace WpfApplication1
    {
        /// <summary>
        /// Interaction logic for Window1.xaml
        /// </summary>
        public partial class Window1 : Window
        {
            public Window1()
            {
                InitializeComponent();
                this.Loaded += new RoutedEventHandler(Window1_Loaded);
            }
    
            void Window1_Loaded(object sender, RoutedEventArgs e)
            {
                var permissions = new List<Permission>();
    
                for (var i = 0; i < 10; i++)
                {
                    permissions.Add(new Permission { 
                    IsSelected = false,
                    PermissionDescription = "PermissionDescription"+i,
                    PermissionId =i.ToString()
                    });
                }
    
                lstEmployees.ItemsSource = permissions;
            }
    
    
            private void btnShowSelectedItems_Click(object sender, RoutedEventArgs e)
            {
                var permissions = lstEmployees.ItemsSource as List<Permission>;
                foreach (var item in permissions)
                {
                    if (item.IsSelected == true)
                    {
                        MessageBox.Show((item.PermissionDescription + " is checked."));
    
                    }
                }
            }
    
            private void lst_SelectionChanged(object sender, RoutedEventArgs e)
            {           
                var listBox = sender as ListBox;
                if (listBox.SelectedIndex > -1)
                {
                    var permission = listBox.SelectedItem as Permission;
    
                    Console.WriteLine(lstEmployees.SelectedIndex);
                    Console.WriteLine(((CheckBox)lstEmployees.SelectedItem).IsChecked);
                }
            }
        }
    
        public class Permission
        {
            public string PermissionDescription { get; set; }
            public string PermissionId { get; set; }
            public bool IsSelected { get; set; }
        }
    }
    

    Follow my above code and let me know if you any more doubts

    Thanks & Regards
    Syed Amjad Sr. Silverlight/WPF Developer,
    yahoo : syedamjad6736@yahoo.com, skype : syedamjad.0786.
    Please use Marked as Answer if my post solved your problem and use Vote As Helpful if a post was useful.

    • Marked as answer by Doudy_Egypt Sunday, June 30, 2013 10:10 AM
    Sunday, June 30, 2013 6:23 AM

All replies

  • <Window x:Class="WpfApplication1.Window1"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Window1" Height="300" Width="300">
        <Window.Resources>
            <DataTemplate x:Key="NameColumnTemplate">
                <CheckBox Height="20"  FontFamily="Arial" FontSize="14"  Content="{Binding Path=PermissionDescription}" 
                          Tag="{Binding PermissionID}" IsChecked="{Binding IsSelected, Mode=TwoWay}" HorizontalAlignment="Stretch" VerticalAlignment="Center"
                          />
            </DataTemplate>
        </Window.Resources>
        <Grid>
            <ListBox HorizontalAlignment="Stretch" Margin="12,12,136,21" Name="lstEmployees" 
                              VerticalAlignment="Stretch" ItemsSource="{Binding Tables[0]}"  
                              ItemTemplate="{StaticResource NameColumnTemplate}" 
                              ScrollViewer.VerticalScrollBarVisibility="Auto" 
                             BorderBrush="#FFAD7F30"  
                     SelectionChanged="lst_SelectionChanged" CheckBox.Click="lst_SelectionChanged"/>
            <Button Content="listbox" Height="23" HorizontalAlignment="Left" Margin="214,207,0,0" Name="btnShowSelectedItems" 
                    VerticalAlignment="Top" Width="75" Click="btnShowSelectedItems_Click" />
        </Grid>
    </Window>
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;
    
    namespace WpfApplication1
    {
        /// <summary>
        /// Interaction logic for Window1.xaml
        /// </summary>
        public partial class Window1 : Window
        {
            public Window1()
            {
                InitializeComponent();
                this.Loaded += new RoutedEventHandler(Window1_Loaded);
            }
    
            void Window1_Loaded(object sender, RoutedEventArgs e)
            {
                var permissions = new List<Permission>();
    
                for (var i = 0; i < 10; i++)
                {
                    permissions.Add(new Permission { 
                    IsSelected = false,
                    PermissionDescription = "PermissionDescription"+i,
                    PermissionId =i.ToString()
                    });
                }
    
                lstEmployees.ItemsSource = permissions;
            }
    
    
            private void btnShowSelectedItems_Click(object sender, RoutedEventArgs e)
            {
                var permissions = lstEmployees.ItemsSource as List<Permission>;
                foreach (var item in permissions)
                {
                    if (item.IsSelected == true)
                    {
                        MessageBox.Show((item.PermissionDescription + " is checked."));
    
                    }
                }
            }
    
            private void lst_SelectionChanged(object sender, RoutedEventArgs e)
            {           
                var listBox = sender as ListBox;
                if (listBox.SelectedIndex > -1)
                {
                    var permission = listBox.SelectedItem as Permission;
    
                    Console.WriteLine(lstEmployees.SelectedIndex);
                    Console.WriteLine(((CheckBox)lstEmployees.SelectedItem).IsChecked);
                }
            }
        }
    
        public class Permission
        {
            public string PermissionDescription { get; set; }
            public string PermissionId { get; set; }
            public bool IsSelected { get; set; }
        }
    }
    

    Follow my above code and let me know if you any more doubts

    Thanks & Regards
    Syed Amjad Sr. Silverlight/WPF Developer,
    yahoo : syedamjad6736@yahoo.com, skype : syedamjad.0786.
    Please use Marked as Answer if my post solved your problem and use Vote As Helpful if a post was useful.

    • Marked as answer by Doudy_Egypt Sunday, June 30, 2013 10:10 AM
    Sunday, June 30, 2013 6:23 AM
  • Thanks a lot Syed Amjad, That 's work for me, but I have another question please

    private void btnShowSelectedItems_Click(object sender, RoutedEventArgs e)
            {
                List<Permission> permissions = lstEmployees.ItemsSource as List<Permission>;
                    foreach (var item in permissions)
                    {
                        if (item.IsSelected == true)
                        {
                            System.Windows.MessageBox.Show((item.PermissionId + " is checked."));
    
                        }
                        else
                        {
                            System.Windows.MessageBox.Show("no item selected");
                        }
                    }
            }
    when there is no item checked , the message repeat several times , what I means If my list has 10 items and no item checked the message appear 10 times, How can I avoid that?



    • Edited by Doudy_Egypt Monday, July 1, 2013 9:21 PM Help
    Sunday, June 30, 2013 10:11 AM
  • this button work only for one time if user second time click button then nothing happen

    Saturday, July 28, 2018 7:41 PM
  • Yes, you will see 10 messages because you have 10 records and for loop iterates for 10 times.

    In such a case, break the loop in else condition(once it shows the first time) and exit from the method


    Thanks & Regards
    Syed Amjad Sr. Silverlight/WPF Developer,
    yahoo : syedamjad6736@yahoo.com, skype : syedamjad.0786.
    Please use Marked as Answer if my post solved your problem and use Vote As Helpful if a post was useful.

    Wednesday, August 15, 2018 3:58 AM
  • whenever you click the button it will prompt you the same messages for n number of records. 

    share your code to understand better


    Thanks & Regards
    Syed Amjad Sr. Silverlight/WPF Developer,
    yahoo : syedamjad6736@yahoo.com, skype : syedamjad.0786.
    Please use Marked as Answer if my post solved your problem and use Vote As Helpful if a post was useful.

    Wednesday, August 15, 2018 3:59 AM