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

Ron McCain
Ron McCain used Ask the Experts™
on
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
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
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 Engineer

Author

Commented:
thank you very much, will try this right away
thank you for the fast response
Ron McCainSenior Software Engineer

Author

Commented:
could you please show the sql standard c# database access instead of using your entity code
Thanks
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Ron McCainSenior Software Engineer

Author

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 Engineer

Author

Commented:
thanks for the non-reply
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

Ron McCainSenior Software Engineer

Author

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

Author

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 Engineer

Author

Commented:
got your message. i will prepare something and send it . thanks very much

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial