We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
close icon

How can i change backcolor of last cell in selected row on KeyPress in Datagrid?

Hello, i want to change the background color of one cell in selected row when pressing ctrl + J. How can i do this?


7 Replies 1 reply marked as answer

VS Vijayarasan Sivanandham Syncfusion Team November 21, 2022 06:39 PM UTC

Hi Christoph Beerwald,

Your requirement to change the back color of the last cell in the selected row on KeyPress in SfDataGrid can be achieved by customizing the PreviewKeyDown and SelectionChanged events. Refer to the below code snippet,


XAML Code Snippet:

<Application.Resources>

     <local:SelectorClass x:Key="styleSelector"/>

     <Style x:Key="highlightCell" TargetType="syncfusion:GridCell">

         <Setter Property="Background" Value="Red" />

     </Style>

 </Application.Resources>

 

 

<syncfusion:SfDataGrid x:Name="sfDataGrid"                         

                       ItemsSource="{Binding Orders}"

                       SelectionMode="Extended"

                       CellStyleSelector="{StaticResource styleSelector}"

                       AutoGenerateColumns="False"/>


C# code snippet for updating the cell style at runtime:

//Event customization

private void OnSelectionChanged(object sender, GridSelectionChangedEventArgs e)

{

    if(e.RemovedItems.Count > 0)

    {

        foreach (var record in e.RemovedItems)

        {

            //If you need to remove the applied style in SfDataGrid for the selection of removed records

            //by calling the UpdateDataRow method to update the style at runtime in SfDataGrid

            this.AssociatedObject.UpdateDataRow((record as GridRowInfo).RowIndex);

        }

    }

}

 

//Event customization

private void OnPreviewKeyDown(object sender, KeyEventArgs e)

{

    //Here customize based on your scenario

    if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.J)

    {

        foreach(var record in this.AssociatedObject.SelectedItems)

        {

            //here get the RowIndex of the updated cell value

            var rowIndex = this.AssociatedObject.ResolveToRowIndex(record);

            //Change the Row Style at runtime by updating the value changed row index in SfDataGrid.

            this.AssociatedObject.UpdateDataRow(rowIndex);

        }

    }

}


UG Link: https://help.syncfusion.com/wpf/datagrid/helpers

https://help.syncfusion.com/wpf/datagrid/selection#selectionchanged-event

C# Code Snippet for StyleSelector:

public class SelectorClass : StyleSelector

{

    public override Style SelectStyle(object item, DependencyObject container)

    {

        var gridCell = container as GridCell;

 

        if (gridCell != null && gridCell.ColumnBase != null)

        {

            var column = gridCell.ColumnBase.GridColumn;

 

            if (column != null)

            {

                var sfDataGrid = column.GetType().GetProperty("DataGrid", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(column) as SfDataGrid;

 

                if (sfDataGrid != null)

                {

                    foreach (var record in sfDataGrid.SelectedItems)

                    {

                        var rowIndex = sfDataGrid.ResolveToRowIndex(record);

 

                        if (gridCell.ColumnBase.RowIndex == rowIndex && gridCell.ColumnBase.ColumnIndex == sfDataGrid.GetLastColumnIndex())

                        {

                            //Here apply the style based on your scenario

                            return App.Current.Resources["highlightCell"] as Style;

                        }

                    }

                }

            }

        }

 

        return base.SelectStyle(item, container);

    }

}


For more information related to conditional styling, please refer to the below user guide documentation link,

UG Link: https://help.syncfusion.com/wpf/datagrid/conditional-styling?cs-save-lang=1&cs-lang=xaml#conditional-styling-of-cells-using-style-selector

https://help.syncfusion.com/wpf/datagrid/conditional-styling?cs-save-lang=1&cs-lang=xaml#condition-styling-of-cells-based-on-record-using-converter

https://help.syncfusion.com/wpf/datagrid/conditional-styling?cs-save-lang=1&cs-lang=xaml#conditional-styling-of-rows-using-style-selector

KB Link: https://www.syncfusion.com/kb/5992/how-to-change-the-gridcell-style-at-runtime

Find the sample in the attachment.

Regards,

Vijayarasan S


If this post is helpful, please consider Accepting it as the solution so that other members can locate it more quickly.


Attachment: SfDataGridDemo_ca856059.zip


CB Christoph Beerwald November 22, 2022 08:30 PM UTC

Hello, thanks for the quick help. I still can't get any further. now it says the assembly reference to "local:SelectorClass" is missing. unfortunately i don't know which reference to add.

is it possible that i can return a color? I would like to change the color green by pressing the "ctrl + j" keys, red by "ctrl+n" and white by "ctrl+x".


Thank you!



VS Vijayarasan Sivanandham Syncfusion Team November 23, 2022 07:20 PM UTC

Christoph Beerwald,

Find the responses to your queries below.

Queries

Responses

Hello, thanks for the quick help. I still can't get any further. now it says the assembly reference to "local:SelectorClass" is missing. unfortunately i don't know which reference to add.


The reported problem occurs due to a mismatched namespace defined for SelectorClass. Refer to the below-mentioned screenshot,




You can resolve the reported problem by defining the proper namespace for App.xaml. Refer to the below-mentioned screenshot,

 

 

is it possible that i can return a color? I would like to change the color green by pressing the "ctrl + j" keys, red by "ctrl+n" and white by "ctrl+x".

 


Your requirement can be achieved by customizing the PreviewKeyDown event as shown below code snippet,

//Event customization

 private void OnPreviewKeyDown(object sender, KeyEventArgs e)

 {

     //Here customize based on you scenario

     if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.J)

     {

         foreach(var record in this.AssociatedObject.SelectedItems)

         {

             //here get RowIndex of the updated cell value

             var rowIndex = this.AssociatedObject.ResolveToRowIndex(record);

             RowColumnIndex rowColumnIndex = new RowColumnIndex(rowIndex, AssociatedObject.GetLastColumnIndex());

             //Here pass the color, datagrid and RowColumnIndex based on your scenario

             ChangeTheLastCellStyle(AssociatedObject, rowColumnIndex, Colors.Green);

         }

     }

 

     //Here customize based on you scenario

     if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.N)

     {

         foreach (var record in this.AssociatedObject.SelectedItems)

         {

             //here get RowIndex of the updated cell value

             var rowIndex = this.AssociatedObject.ResolveToRowIndex(record);

             RowColumnIndex rowColumnIndex = new RowColumnIndex(rowIndex, AssociatedObject.GetLastColumnIndex());

             //Here pass the color, datagrid and RowColumnIndex based on your scenario

             ChangeTheLastCellStyle(AssociatedObject, rowColumnIndex, Colors.Red);

         }

     }

 

     //Here customize based on you scenario

     if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && e.Key == Key.X)

     {

         foreach (var record in this.AssociatedObject.SelectedItems)

         {

             //here get RowIndex of the updated cell value

             var rowIndex = this.AssociatedObject.ResolveToRowIndex(record);

             RowColumnIndex rowColumnIndex = new RowColumnIndex(rowIndex, AssociatedObject.GetLastColumnIndex());

             //Here pass the color, datagrid and RowColumnIndex based on your scenario

             ChangeTheLastCellStyle(AssociatedObject, rowColumnIndex, Colors.White);

         }

     }

 }

 

 //Helper method to change the color

 public void ChangeTheLastCellStyle(SfDataGrid dataGrid, RowColumnIndex rowColumnIndex, Color color)

 {

     DataRowBase dataRow = null;

     List<DataColumnBase> visibleColumns = null;

 

     //here get the all datarows in SfDataGrid

     foreach (var item in dataGrid.GetRowGenerator().Items)

     {

         if (item != null)

         {

             //Get datarow

             dataRow = item as DataRowBase;

 

             if (dataRow != null)

             {

                 //Get visible columns

                 visibleColumns = dataRow.VisibleColumns;

 

                 if (visibleColumns != null)

                 {

                     foreach (var column in visibleColumns)

                     {

                         if (column != null)

                         {

                             //her customize based on your scenario

                             if (column.ColumnIndex == rowColumnIndex.ColumnIndex && column.RowIndex == rowColumnIndex.RowIndex)

                             {

                                 FrameworkElement columnElement = column.ColumnElement;

                                 if (columnElement != null)

                                 {

                                     if (!(columnElement is GridHeaderCellControl))

                                     {

                                         //Get the GridCell

                                         GridCell gridCell = columnElement as GridCell;

 

                                         //here customize based on your scenario

                                         //Change the GridCell Style

                                         if (gridCell != null)

                                         {

                                             Style style = new Style(typeof(GridCell));

                                             style.Setters.Add(new Setter(GridCell.BackgroundProperty, new SolidColorBrush(color)));

                                             gridCell.Style = style;

                                         }

                                     }

                                 }

                             }

                         }

                     }

                 }

             }

         }

 

     }

 }


Find the modified sample in the attachment.

If this post is helpful, please consider Accepting it as the solution so that other members can locate it more quickly.


Attachment: ModifiedSample_e916eb2e.zip


CB Christoph Beerwald November 23, 2022 07:57 PM UTC

That was exactly what i was looking for, thank you very much!



VS Vijayarasan Sivanandham Syncfusion Team November 24, 2022 05:33 AM UTC

Christoph Beerwald,

We are glad to know that the reported problem has been resolved at your end. Please let us know if you have any further queries on this. We are happy to help you
😊.



CB Christoph Beerwald November 24, 2022 06:03 AM UTC

Hello,

how can i export a sfdatagrid as excelfile with colored cells and import excelfile to sfdatagrid with colored cells?



VS Vijayarasan Sivanandham Syncfusion Team November 24, 2022 02:20 PM UTC

Christoph, Please follow the newly created ticket for further updates


Marked as answer
Loader.
Live Chat Icon For mobile
Up arrow icon