URGENT - dynamically change background color of a datagrid row based on database column value

I have a C# WPF PROJECT AND NEED A COMPLETE SOLUTION TO DO THE FOLLOWING.

1. Change the color of a WPF datagrid cell when my sql database query finds a true or a false on specific database columns
2. I need to change the color in the same column/row  where the true/false is located.
3. I need to continue to do this as long as the database is being queried.
This request for help is very urgent. Please assist. If you work for hire I will pay as well.
Thanks
Ron McCainSenior Software EngineerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Anil GolamariCommented:
Hi,

Below is sample that I have created which should be able to give you working code. But I am not sure about 3 point as I don't have much sample data to insert I just created for 3 rows that I build for this sample.

Also I have used entity framework to make the database connection and fill up the datagrid.

<Window x:Class="SampleWpf.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SampleWpf"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="41*"/>
                <RowDefinition Height="183*"/>
                <RowDefinition Height="45*"/>
            </Grid.RowDefinitions>
            <TextBlock Text="Employees"    
FontSize="25"    
Foreground="Chocolate"    
Grid.Row="0"    
VerticalAlignment="Top"    
Margin="10,5,0,0"/>
            <DataGrid Name="SampleGrid"    
Grid.Row="1"    
AutoGenerateColumns="False"    
Margin="10,5,0,0"    
Height="200"    
Width="450"    
HorizontalAlignment="Left"    
ItemsSource="{Binding Path=LoadDataBinding}"    
CanUserResizeRows="False"    
CanUserAddRows="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}" IsReadOnly="True" Width="80"/>
                    <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" IsReadOnly="True" Width="120"/>
                    <DataGridTextColumn Header="Wanttorevealrace" Binding="{Binding Path=Wanttorevealrace}" IsReadOnly="True" Width="120">
                        <DataGridTextColumn.ElementStyle>
                            <Style TargetType="{x:Type TextBlock}">
                                <Style.Triggers>
                                    <Trigger Property="Text" Value="False">
                                        <Setter Property="Background" Value="LightGreen"/>
                                    </Trigger>
                                </Style.Triggers>
                            </Style>
                        </DataGridTextColumn.ElementStyle>
                    </DataGridTextColumn>
                </DataGrid.Columns>
            </DataGrid>
            <Button Name="btndisplaydata"    
Content="Display Data"    
HorizontalAlignment="Left"    
VerticalAlignment="Top"    
Grid.Row="2"    
Margin="320,5,10,3"    
Height="35"    
Width="140"    
FontSize="20"    
Click="btndisplaydata_Click"/>
        </Grid>
    </StackPanel>

</Window>

Open in new window

     
  private void btndisplaydata_Click(object sender, RoutedEventArgs e) {
            try {
                GolamariEntities Con = new GolamariEntities();
                List<wpfsample> TableData = Con.wpfsamples.ToList();
                SampleGrid.ItemsSource = TableData;
                }
            catch(Exception ex) {
                MessageBox.Show(ex.ToString());
                }
            }

Open in new window


Not sure if the sample db of any use for you but just want to paste it if you want to go through it.

Create Table wpfsample(ID int Primary Key identity(1,1), 
					   Name nvarchar(256),
					   Wanttorevealrace Bit); 

select * from dbo.wpfsample

Insert INTO dbo.wpfsample (Name, Wanttorevealrace) 
select 'John', 0 
Union All select 'Mike', 1 
Union All select 'Mat', 0

Open in new window

Ron McCainSenior Software EngineerAuthor Commented:
thank you very much, will try this right away
thank you for the fast response
Ron McCainSenior Software EngineerAuthor Commented:
could you please show the sql standard c# database access instead of using your entity code
Thanks
Your Guide to Achieving IT Business Success

The IT Service Excellence Tool Kit has best practices to keep your clients happy and business booming. Inside, you’ll find everything you need to increase client satisfaction and retention, become more competitive, and increase your overall success.

Ron McCainSenior Software EngineerAuthor Commented:
cant get your solution to work, could you please try again with generic sql commands and a brief explanation for what you are doing
Ron McCainSenior Software EngineerAuthor Commented:
thanks for the non-reply
Anil GolamariCommented:
Code you are looking for.  There are no changes in the UI.

using System;
using System.Configuration;
using System.Windows;
using System.Data;
using System.Data.SqlClient;


namespace SampleWpf {
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
            FillDataGrid();
            }

        /// <summary>
        /// Method to Fill data in the grid from Sql Server database without using Entity framework.
        /// </summary>
        private void FillDataGrid() {
            //Pulling connectionstring information from Appsettings.
            string connstring = ConfigurationManager.ConnectionStrings["GolamariEntities"].ConnectionString;
            string CmdString = string.Empty;
            // I have used using statement so that database connection can be disposed once we are done with out transaction.
            using(SqlConnection con = new SqlConnection(connstring)) {
                // Sql Statement you we have to run against the database.
                CmdString = "select * from dbo.wpfsample";
                SqlCommand cmd = new SqlCommand(CmdString, con);
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                //Data from the database will be filled into datatable.
                DataTable dt = new DataTable("wpfsample");
                sda.Fill(dt);
                //Data from datatable will be filled into Grid.
                SampleGrid.ItemsSource = dt.DefaultView;
                }
            }

        private void btndisplaydata_Click(object sender, RoutedEventArgs e) {
            //try {
            //    GolamariEntities Con = new GolamariEntities();
            //    List<wpfsample> TableData = Con.wpfsamples.ToList();
            //    SampleGrid.ItemsSource = TableData;
            //    }
            //catch(Exception ex) {
            //    MessageBox.Show(ex.ToString());
            //    }

            }
        }
    }

Open in new window


Configuration File:
<connectionStrings>
    <add name="GolamariEntities" connectionString="data source=ANILREDDY\SQLEXPRESS;initial catalog=Golamari;integrated security=True;" />
    <!--<add name="GolamariEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=ANILREDDY\SQLEXPRESS;initial catalog=Golamari;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />-->
  </connectionStrings>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ron McCainSenior Software EngineerAuthor Commented:
we tried for quite some time but could get your solution to work. I think it may be my fault in my explanation. would you be willing to look at my code and integrate a working solution. we will be happy to pay for your services if required
Anil GolamariCommented:
What exactly you are looking for? Because I thought I have posted required code above.  Send me a message about exactly what you are looking for and I can definitely try to help you out.
Ron McCainSenior Software EngineerAuthor Commented:
As I said I'm sure you sent a good solution we just cant seem to integrate it with what we already have.

We will need to integrate the bindings and triggers with our xaml and xaml.cs code and we will need to  use the queried values from our database to trigger the bindings in the xaml file which will color the bound items in the xaml. If you are willing I will send you our files
Ron McCainSenior Software EngineerAuthor Commented:
got your message. i will prepare something and send it . thanks very much
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.