none
Determine which checkboxes checked

    Question

  • I have a series of Checkboxes in my app....based on which ones are selected I am going to run specific code....

    What I am looking for is a simple loop that will determine which checkboxes are checked....

    Anyone have any examples....I am trying to avoid doing a bunc of If then Statements....

    NOTE: I am trying to run this code from a button....the users selects a few options (checkboxes) then hits a button to start the search....in this case just the code that determines which ones are selected.

    THanks

    Thursday, March 10, 2011 9:14 AM

Answers

  • XAML:

    <StackPanel Name="SearchStackPanel2" Orientation="Vertical" Width="185" Margin="10,15,0,0">
        <TextBlock Text="Please Select A couple categories" Foreground="Black" />
        <StackPanel Orientation="Horizontal" >
            <StackPanel Orientation="Vertical" >
                <CheckBox x:Name="Baseball" IsChecked="False" Margin="5,0,0,0" Foreground="Black"  Content="Baseball" />
                <CheckBox x:Name="Hockey" IsChecked="False" Margin="5,0,0,0" Foreground="Black"  Content="Hockey" />
                <CheckBox x:Name="Golfing" IsChecked="False" Margin="5,0,0,0" Foreground="Black" Content="Golfing" />
                <CheckBox x:Name="FrisbeGolf" IsChecked="False" Margin="5,0,0,0" Foreground="Black"  Content="Frisbe Golf" />
            </StackPanel>
            <StackPanel Orientation="Vertical">
                <CheckBox x:Name="Swimming" IsChecked="False" Margin="5,0,0,0" Foreground="Black" Content="Swimming" />
                <CheckBox x:Name="Pavilions" IsChecked="False" Margin="5,0,0,0" Foreground="Black"  Content="Pavilions" />
                <CheckBox x:Name="Hiking" IsChecked="False" Margin="5,0,0,0" Foreground="Black" Content="Hiking" />
                <CheckBox x:Name="Boating" IsChecked="False" Margin="5,0,0,0" Foreground="Black"  Content="Boating" />
            </StackPanel>
        </StackPanel>
        <Button Content="Check" Click="Button_Click" />
    </StackPanel>


     

    C#:

    using System.Collections.Generic;
    using System.Windows;
    using System.Windows.Controls;
    
    namespace SilverlightApplication10
    {
        public partial class MainPage : UserControl
        {
            private List<string> _checkedItems;
    
            public MainPage()
            {
                InitializeComponent();
    
                _checkedItems = new List<string>();
            }
    
            private void Button_Click(object sender, RoutedEventArgs e)
            {
                FindCheckedItems();
    
                Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show(string.Format("{0} items checked", _checkedItems.Count));
                    });
            }
    
            public void FindCheckedItems()
            {
                _checkedItems.Clear();
                ValidateAllCheckBoxes(SearchStackPanel2);
            }
    
            private void ValidateAllCheckBoxes(UIElement element)
            {
                CheckBox cb = element as CheckBox;
    
                if (cb != null)
                {
                    if (cb.IsChecked.HasValue && cb.IsChecked.Value)
                        _checkedItems.Add(cb.Content.ToString());
                }
    
                else
                {
                    Panel p = element as Panel;
                    if (p != null)
                    {
                        foreach(UIElement child in p.Children)
                            ValidateAllCheckBoxes(child);
                    }
                }
            }
        }
    }
    


     

    Thursday, March 10, 2011 10:16 AM
  • Yep.....clean VB converion except for that one line.....I THANK you very much....very appreciated...

    THANK YOU AGAIN

     

    Was this

    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show(string.Format("{0} items checked", _checkedItems.Count));
                    });

    Now this

    MessageBox.Show(String.Format("{0} items checked", _checkedItems.Count))

     

    Thursday, March 10, 2011 10:49 AM

All replies

  • Hi,

    What is that checkbox? Just simple or generate from collection class?

    Thursday, March 10, 2011 9:17 AM
  • If the checkboxes are in a layout, you can loop through the children and check if they are check. 

    foreach (var e in LayoutRoot.Children)
    {
        CheckBox cb = e as CheckBox;
    
        if (cb != null)
        {
            bool isChecked = (cb.IsChecked.HasValue && cb.IsChecked.Value);
        }
                    
    }


     

     

    If the checkboxes are databound, you can also check the object that they are databound to.

    Thursday, March 10, 2011 9:19 AM
  • Hi,

    Use Tag property.

    Example

    <input:AutoCompleteBox ItemsSource="{StaticResource SampleEmployees}" Tag="Value3" SelectionChanged="OnSelectionChanged" Width="230" Grid.Column="1" Margin="0, 8, 0, 8" HorizontalAlignment="Left"/>
                            <ContentPresenter Name="Value3" Grid.Column="2"/>

                            <TextBlock Padding="5" Grid.Row="1">Contains:</TextBlock>
                            <input:AutoCompleteBox FilterMode="Contains" MinimumPrefixLength="1" ItemsSource="{StaticResource SampleEmployees}" Tag="Value4" SelectionChanged="OnSelectionChanged" Width="230" Grid.Row="1" Grid.Column="1" Margin="0, 8, 0, 8" HorizontalAlignment="Left"/>
                            <ContentPresenter Name="Value4" Grid.Row="1" Grid.Column="2"/>

                            <TextBlock Padding="5" Grid.Row="2">StartsWithCaseSensitive:</TextBlock>

                            <input:AutoCompleteBox FilterMode="StartsWithCaseSensitive" ItemsSource="{StaticResource SampleEmployees}" Tag="Value5" SelectionChanged="OnSelectionChanged" Width="230" Grid.Row="2" Grid.Column="1" Margin="0, 8, 0, 8" HorizontalAlignment="Left"/>
                            <ContentPresenter Name="Value5" Grid.Row="2" Grid.Column="2"/>

     

    private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                AutoCompleteBox acb = (AutoCompleteBox)sender;

                // In these sample scenarios, the Tag is the name of the content
                // presenter to use to display the value.
                string contentPresenterName = (string)acb.Tag;
                ContentPresenter cp = FindName(contentPresenterName) as ContentPresenter;
                if (cp != null)
                {
                    cp.Content = acb.SelectedItem;
                }
            }

    Thursday, March 10, 2011 9:19 AM
  • Right now I just have this.  Is the ItemsSource in your example working like a GroupName on a radion button?  I would like to make these checkboxes work together as I will have other checkboxes in my application....so I assume that i have to change seomthing below to do that....

    If I use your example how can I send the result of which is selected to a messagebox...Messagebox.show(cp)?

     In Visual Studio I do not see a SelectionChanged event on a checkbox????

    I tried to use <input:AutoCompleteBox adn I get assembly reference errors....

    I guess I am asking the best way to do this...I am going to take the result of which checkboxes are checked adn feed that into a query....so I just need to know which ones are checked.... 

    If there is a better way to do this please I would love to know....

     

    <StackPanel Name="SearchStackPanel2" Orientation="Vertical" Visibility="Collapsed" Height="Auto" Width="185" Margin="10,15,0,0">
         <TextBlock Text="Please Select A couple categories" Foreground="Black" />
             <StackPanel Orientation="Horizontal" >
                 <StackPanel Orientation="Vertical" >
                     <CheckBox x:Name="Baseball" IsChecked="False" Margin="5,0,0,0" Foreground="Black"  Content="Baseball" />
                     <CheckBox x:Name="Hockey" IsChecked="False" Margin="5,0,0,0" Foreground="Black"  Content="Hockey" />
                     <CheckBox x:Name="Golfing" IsChecked="False" Margin="5,0,0,0" Foreground="Black" Content="Golfing" />
                     <CheckBox x:Name="FrisbeGolf" IsChecked="False" Margin="5,0,0,0" Foreground="Black"  Content="Frisbe Golf" />
                 </StackPanel>
                 <StackPanel Orientation="Vertical">
                     <CheckBox x:Name="Swimming" IsChecked="False" Margin="5,0,0,0" Foreground="Black" Content="Swimming" />
                     <CheckBox x:Name="Pavilions" IsChecked="False" Margin="5,0,0,0" Foreground="Black"  Content="Pavilions" />
                     <CheckBox x:Name="Hiking" IsChecked="False" Margin="5,0,0,0" Foreground="Black" Content="Hiking" />
                     <CheckBox x:Name="Boating" IsChecked="False" Margin="5,0,0,0" Foreground="Black"  Content="Boating" />
                 </StackPanel>
             </StackPanel>
     </StackPanel>

     

    Thursday, March 10, 2011 9:44 AM
  • thaicarrot's previous post looks like it was intended for another thread.

    Thursday, March 10, 2011 10:03 AM
  • How do I take what I have right now...seen in my previous post...and set it up to be in a layout so I can use the ForEach?

    Can you show a very basic example of the xaml and the cs.....

    Again I am trying to run this code from a button...I want the user to select a few checkboxes...then hit the button to start the code....I am confused on how to get there...

    Thursday, March 10, 2011 10:10 AM
  • XAML:

    <StackPanel Name="SearchStackPanel2" Orientation="Vertical" Width="185" Margin="10,15,0,0">
        <TextBlock Text="Please Select A couple categories" Foreground="Black" />
        <StackPanel Orientation="Horizontal" >
            <StackPanel Orientation="Vertical" >
                <CheckBox x:Name="Baseball" IsChecked="False" Margin="5,0,0,0" Foreground="Black"  Content="Baseball" />
                <CheckBox x:Name="Hockey" IsChecked="False" Margin="5,0,0,0" Foreground="Black"  Content="Hockey" />
                <CheckBox x:Name="Golfing" IsChecked="False" Margin="5,0,0,0" Foreground="Black" Content="Golfing" />
                <CheckBox x:Name="FrisbeGolf" IsChecked="False" Margin="5,0,0,0" Foreground="Black"  Content="Frisbe Golf" />
            </StackPanel>
            <StackPanel Orientation="Vertical">
                <CheckBox x:Name="Swimming" IsChecked="False" Margin="5,0,0,0" Foreground="Black" Content="Swimming" />
                <CheckBox x:Name="Pavilions" IsChecked="False" Margin="5,0,0,0" Foreground="Black"  Content="Pavilions" />
                <CheckBox x:Name="Hiking" IsChecked="False" Margin="5,0,0,0" Foreground="Black" Content="Hiking" />
                <CheckBox x:Name="Boating" IsChecked="False" Margin="5,0,0,0" Foreground="Black"  Content="Boating" />
            </StackPanel>
        </StackPanel>
        <Button Content="Check" Click="Button_Click" />
    </StackPanel>


     

    C#:

    using System.Collections.Generic;
    using System.Windows;
    using System.Windows.Controls;
    
    namespace SilverlightApplication10
    {
        public partial class MainPage : UserControl
        {
            private List<string> _checkedItems;
    
            public MainPage()
            {
                InitializeComponent();
    
                _checkedItems = new List<string>();
            }
    
            private void Button_Click(object sender, RoutedEventArgs e)
            {
                FindCheckedItems();
    
                Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show(string.Format("{0} items checked", _checkedItems.Count));
                    });
            }
    
            public void FindCheckedItems()
            {
                _checkedItems.Clear();
                ValidateAllCheckBoxes(SearchStackPanel2);
            }
    
            private void ValidateAllCheckBoxes(UIElement element)
            {
                CheckBox cb = element as CheckBox;
    
                if (cb != null)
                {
                    if (cb.IsChecked.HasValue && cb.IsChecked.Value)
                        _checkedItems.Add(cb.Content.ToString());
                }
    
                else
                {
                    Panel p = element as Panel;
                    if (p != null)
                    {
                        foreach(UIElement child in p.Children)
                            ValidateAllCheckBoxes(child);
                    }
                }
            }
        }
    }
    


     

    Thursday, March 10, 2011 10:16 AM
  • ...............................................................................

    Thursday, March 10, 2011 10:44 AM
  • Yep.....clean VB converion except for that one line.....I THANK you very much....very appreciated...

    THANK YOU AGAIN

     

    Was this

    Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show(string.Format("{0} items checked", _checkedItems.Count));
                    });

    Now this

    MessageBox.Show(String.Format("{0} items checked", _checkedItems.Count))

     

    Thursday, March 10, 2011 10:49 AM
  • ONE FINAL QUESTION....I can get the count to work fine...it tells me how many were selected...

    I cant see anything that will give me the name of the Checkbox that is selected....I want to take this name and then run some code based off it...

    If 'Hockey' is selected then I am going to run a Hockey query to return Hockey results....so If I get a list I can parse through the list and run an If Then sceniro to run the proper queries...

    The only think I saw was

     

    MessageBox.Show(String.Format("{0} items checked", _checkedItems.Count))

    MessageBox.Show(String.Format("{0} items checked", _checkedItems.Item)) 

     

    I would like to get a list of the checkbox names...and put them in the messagebox...

     

     

     

    Thursday, March 10, 2011 11:19 AM
  • I can slip this in, but it does not get the checkbox values back to the original sub where I called FindCheckedItemsSearchStackPanel()

    Now I can test the Checkboxes adn determine if a value was checked...

    If there is a value then I need to test for the Content Name to fire off specific code

    So I need the content values back in the main sub to fire then off....I cant seem to get the Content Value back into the main sub...I can only send it to a messagebox in the "ValidateAllCheckBoxes"

    Any thoughts

     

             If cb IsNot Nothing Then
                If cb.IsChecked.HasValue AndAlso cb.IsChecked.Value Then
                    _checkedItems.Add(cb.Content.ToString())
                    MessageBox.Show(cb.Content.ToString)
             End If

     

    MAYBE SOMETHING LIKE THIS:

     

    Private Sub GetSelectedValues(ByVal sender As Object, ByVal e As RoutedEventArgs)

         ' Find which checkboxes are checked in the SearchStackPanel2
            FindCheckedItemsSearchStackPanel()
            Dim varStackPanel As String = ""
            varStackPanel = String.Format("{0} items checked", _checkedItems.Count)
            MessageBox.Show(varStackPanel)
      

           ' TEST TO SEE IF THERE IS A CHECKBOX CHECKED


            If _checkedItems.Content = "Baseball" Then
                     ' DO SOMETHING
           ElseIf _checkedItems.Content = "Hockey" Then
                     ' DO SOMETHING
           Else
                     ' DO SOMETHING
           End If
             
    End Sub  
     
    Public Sub FindCheckedItemsSearchStackPanel()
            _checkedItems.Clear()
            ValidateAllCheckBoxes(SearchStackPanel)
    End Sub
     
    Private Sub ValidateAllCheckBoxes(ByVal element As UIElement)
            Dim cb As CheckBox = TryCast(element, CheckBox)

            If cb IsNot Nothing Then
                If cb.IsChecked.HasValue AndAlso cb.IsChecked.Value Then
                    _checkedItems.Add(cb.Content.ToString())
                    MessageBox.Show(cb.Content.ToString)
                End If
            Else
                Dim p As Panel = TryCast(element, Panel)
                If p IsNot Nothing Then
                    For Each child As UIElement In p.Children
                        ValidateAllCheckBoxes(child)
                    Next
                End If
            End If
    End Sub

    Thursday, March 10, 2011 4:26 PM
  • Got it.....I just put this in...Instead of my If then statement seen in my last post...

    REMOVED THIS

    If _checkedItems.Content = "Baseball" Then
                     ' DO SOMETHING
           ElseIf _checkedItems.Content = "Hockey" Then
                     ' DO SOMETHING
           Else
                     ' DO SOMETHING
           End If

    ADDED THIS

    For Each s As String In _checkedItems
                MessageBox.Show(s)
    Next

     

     THANKS FOR YORU HELP FuryDiamond ..leaning a bit more every day....thanks again....very appreciated.

     

    Friday, March 11, 2011 9:59 AM