DataGrid data row based on cell value

I am currently working on a C # WPF datagrid. I have a DataGrid that has auto-generated columns, and the code connects to a SQLite database and creates a data set, and then this data set is set as a DataGrid ItemsSource data element.

Below is the code with XAML 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 for setting ItemsSource for 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 displayed in the database (automatically generated) are ID, date, time, status. What I need to do is if the value in the row of the status column is Error to change the background color of this row.

I assume that I need to add style tags and DataTriggers to the DataGrid tags, but I don't know what I need. Everything I tried for the code that sets the ItemsSource element shows an error saying that the source must be empty before adding the ItemsSource.

Thanks for any help you can provide.

+7
source share
1 answer

You can use DataTrigger for this.

Here is a small example. I created a class called Person with the Name, Age, and Active properties.

 public class Person { public string Name { get; set; } public int Age { get; set; } public bool Active { get; set; } } 

In the designer of the main window, I add 3 Person objects to the list, and then bind this 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 XAML for 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 the value from the Active field from the Person object that is in the DataGridRow, and if this value is false, then it goes into the background color of the row before red.

+20
source

All Articles