Search code examples
c#wpf

WPF Datagrid color based off SQL result


I have been trying lots of different things to change the cell color for the row that returns a "1" from a certain column. I have been hitting a brick wall on all my attempts.

Here is what I'm looking at - this is my selection if column has "1":

My xaml for the JobId if value is true.

<DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
        <Setter Property="IsHitTestVisible" Value="False"></Setter>
        <Style.Triggers>
            <DataTrigger Binding="{Binding Suspended}" Value="Running">
                <Setter Property="Background" Value="#FFEA2B0D"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</DataGrid.RowStyle>
<DataGrid.Columns >
    <DataGridTextColumn Binding="{Binding Id}"  Width="40" Header=" Job ID " Foreground="Black" IsReadOnly="True" >
        <DataGridTextColumn.HeaderStyle>
            <Style TargetType="{x:Type DataGridColumnHeader}">
                <Setter Property="Background" Value="#FF8A8A8A"/>
            </Style>
        </DataGridTextColumn.HeaderStyle>
    </DataGridTextColumn>


string lbcompjob = ("SELECT * FROM " + Table + "  WHERE [cancled] = 1");

SqlCommand cmd = new SqlCommand(lbcompjob, conn);
{
    try
    {
        conn.Open();

        using (SqlDataReader dr = cmd.ExecuteReader())
        {
            while (dr.Read())
            {
                string can = dr[0].ToString();

                if (can == "1")
                {
                    // If True change row color
                }
            }
        }
    }
    catch (Exception ex)
    {
    }
}

Solution

  • Just add a trigger to the RowStyle:

    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="IsHitTestVisible" Value="False" />
    
            <Style.Triggers>
                <DataTrigger Binding="{Binding Suspended}" Value="Running">
                    <Setter Property="Background" Value="#FFEA2B0D"/>
                </DataTrigger>
    
                <!-- Add your trigger here -->
                <DataTrigger Binding="{Binding MyColumn}" Value="1">
                    <Setter Property="Background" Value="Red"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>