views:

1719

answers:

2

Hi all,

I need to assign a color to the a row that i add at runtime to the DataTable. How can this be done ?

Regards Abdul khaliq

+4  A: 

You can handle the DataGrid's LoadingRow event to detect when a row is being added. In the event handler you can get a reference to the DataRow that was added to the DataTable that is acting as your ItemsSource. Then you can update the DataGridRow's color however you like.

void dataGrid_LoadingRow(object sender, Microsoft.Windows.Controls.DataGridRowEventArgs e)
{
    // Get the DataRow corresponding to the DataGridRow that is loading.
    DataRowView item = e.Row.Item as DataRowView;
    if (item != null)
    {
     DataRow row = item.Row;

            // Access cell values values if needed...
            // var colValue = row["ColumnName1]";
            // var colValue2 = row["ColumName2]";

     // Set the background color of the DataGrid row based on whatever data you like from 
     // the row.
     e.Row.Background = new SolidColorBrush(Colors.BlanchedAlmond);
    }   
}

To sign up for the event in XAML:

<toolkit:DataGrid x:Name="dataGrid"
    ...
    LoadingRow="dataGrid_LoadingRow">

Or in C#:

this.dataGrid.LoadingRow += new EventHandler<Microsoft.Windows.Controls.DataGridRowEventArgs>(dataGrid_LoadingRow);
Jeremy
make sure to assign defaults for rows whose color isn't triggered by a condition
Simon_Weaver
+1  A: 

IMPORTANT : be sure to always assign defaults for rows that aren't being colored by a condition - or any other style.

See my answer to C# Silverlight Datagrid - Row Color Change.

PS. I am in Silverlight and haven't confirmed this behavior in WPF

Simon_Weaver