I am currently working on a C# WPF datagrid. I have a DataGrid which has auto generated columns and the code connects to an SQLite Database and creates a dataset and then this dataset is set as the DataGrid ItemsSource.
Below is the code with the XAML of the DataGrid
<DataGrid AutoGenerateColumns="True"
Margin="12,71,12,32"
Name="tblLog"
ColumnWidth="*"
CanUserResizeRows="False"
AreRowDetailsFrozen="False"
CanUserAddRows="True"
CanUserDeleteRows="True"
IsReadOnly="True"
MouseDoubleClick="tblLog_MouseDoubleClick">
</DataGrid>
And below is the code to set the ItemsSource for the DataGrid
try
{
DataSet ds = new DataSet();
SQLiteDataAdapter da = new SQLiteDataAdapter(query, db.conn);
da.Fill(ds);
//tblGrid.AutoGenerateColumns = true;
tblGrid.ItemsSource = ds.Tables[0].DefaultView;
}
catch (SQLiteException ex)
{
MessageBox.Show("Unable to retrieve logins from database.\n\n" + ex.Message + "\n\nError Code: " + ex.ErrorCode);
}
The columns that are shown in the database (auto generated) are ID, date, time, status. What I need to be able to do is if the value in a row of the status column equals Error change the background colour of that row.
I assume I need to add some sort of styling tags and DataTriggers within the DataGrid tags but not sure what I need. Anything I have tried to the code that sets the ItemsSource displays an error saying that the Source needs to be empty before adding the ItemsSource.
Thanks for any help you can provide.
You can use a DataTrigger to do this.
Here is a quick sample. I created a class called Person with the properties Name, Age, and Active.
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public bool Active { get; set; }
}
In the constructor of the main window, I add 3 Person
objects to a list, then bind that list to the DataGrid
.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<Person> people = new List<Person>();
people.Add(new Person()
{
Name = "John Doe",
Age = 32,
Active = true
});
people.Add(new Person()
{
Name = "Jane Doe",
Age = 30,
Active = true
});
people.Add(new Person()
{
Name = "John Adams",
Age = 64,
Active = false
});
tblLog.ItemsSource = people;
}
}
Then in the XAML for the MainWindow, I create a DataTrigger style as a resource.
<Window.Resources>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding Active}" Value="False">
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
What this trigger does is it takes the value from the Active
field from the Person
object that is in the DataGridRow, and if that value is false, then it turns to background color of the row to red.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With