Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C#/WPF: Looping through DataGrid CheckBoxColumn – failing to trigger code at the right time

With the method beneath, I am trying to trigger code for each row in a DataGrid CheckBoxColumn that I am looping through. It works! What doesn’t work, is that I also want to trigger another set of code if ALL of the boxes are unchecked.
Right now, it triggers the code no matter how many boxes are unchecked, unless I check the first one. I tried using a boolean flag to jump out of the loop

How can I re-write my method to achieve the desired result?
My CheckBoxColumn is not three-state, I haven’t looked into that, and I’d rather not, unless absolutely neccessary.

public void VerifyInvoices() {

    foreach (PaidTrip item in PaidTrips) {

        if (item.IsChecked == true) {

            ShowPreviewInvoiceDetailed();
            First = false;

        } else if (item.IsChecked == false && First == true) {

            MessageBox.Show("You must choose an invoice to preview first.");
            return;
        }
    }
}

My CheckBoxColumn:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<DataGridCheckBoxColumn
    Width="146" HeaderStyle="{StaticResource CenterGridHeaderStyle}"
    Binding="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}">

    <DataGridCheckBoxColumn.ElementStyle>
        <Style TargetType="{x:Type CheckBox}">
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="ClickMode" Value="Press"/>
        </Style>
    </DataGridCheckBoxColumn.ElementStyle>
</DataGridCheckBoxColumn>

>Solution :

You can check if all items meet a condition with LINQ:

...
if (item.IsChecked == true) {

    ShowPreviewInvoiceDetailed();
    First = false;

} else 
  {
    if(PaidTrips.All(t => t.IsChecked == false))
    {
        MessageBox.Show("You must choose an invoice to preview first.");
        return;
    }           
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading