Home > database >  C#/WPF: Looping through DataGrid CheckBoxColumn - failing to trigger code at the right time
C#/WPF: Looping through DataGrid CheckBoxColumn - failing to trigger code at the right time

Time:01-15

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:

<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>

CodePudding user response:

show MessageBox only after all PaidTrips were verified and only if there were no checked found:

public void VerifyInvoices()
{
    bool success = false;
    foreach (PaidTrip item in PaidTrips) 
    {
        if (item.IsChecked == true) 
        {
            ShowPreviewInvoiceDetailed();
            success = true;
        }
    }
    if (!success) 
    {
        MessageBox.Show("You must choose an invoice to preview first.");
    }
}

CodePudding user response:

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;
    }           
}
  •  Tags:  
  • Related