Selection in Windows Forms DataGrid (SfDataGrid)

24 May 202324 minutes to read

Windows Forms DataGrid (SfDataGrid) allows you to select one or more rows or cells. For selecting a specific row or group of rows, set the SelectionUnit as row. For selecting a specific cell or group of cells, set the SelectionUnit as cell or Any.In SelectionUnit.Any option. A row can be selected by clicking its row header.

Current cell navigation

Keyboard navigation through the cells and rows is determined based on the NavigationMode property. The NavigationMode.Cell allows you to navigate between the cells in a row and between the rows. The NavigationMode.Row allows you to navigate between the rows. It is not possible to set the NavigationMode.Row when the cell selection is enabled (SelectionUnit is cell or any).

Selection modes

The SelectionUnit and SelectionMode properties defines the behavior of selection in SfDataGrid. If the SelectionMode is single, a single row or cell can be selected. If the SelectionMode is extended or multiple, multiple rows or cells can be selected. The selection can be disabled by changing the SelectionMode as none.

Single row or cell selection

If the SelectionMode is Single, a single row or cell can be selected. SfDataGrid allows you to select or deselect a single row or cell, when the SelectionMode is SingleDeselect.

this.sfDataGrid1.SelectionMode = GridSelectionMode.Single;
Me.sfDataGrid1.SelectionMode = GridSelectionMode.Single

The following image shows for a single mode row selection.

Windows forms datagrid showing single mode row selection

The following image shows for a single mode cell selection.

Windows forms datagrid showing single mode cell selection

NOTE

When the SelectionMode is SingleDeselect, a single row or cell can be selected or deselected by clicking the respective row and cell or by pressing Space key.

Multiple row or cell selection

SfDataGrid allows you to select multiple rows or cells by setting the SelectionMode property as Extended or Multiple by dragging the mouse on SfDataGrid and using key modifiers.

When using extended and multiple modes, the rows or cells can be selected by pressing the key modifiers: Ctrl and Shift.

this.sfDataGrid1.SelectionMode = GridSelectionMode.Extended;
Me.sfDataGrid1.SelectionMode = GridSelectionMode.Extended

The following image shows for extended mode row selection.

Windows forms datagrid showing extended mode row selection

The following image shows for extended mode cell selection.

Windows forms datagrid showing extended mode cell selection

NOTE

When the SelectionMode is Multiple, multiple rows or cells can be selected or deselected by clicking the respective rows or cells. In multiple selection, pressing navigation keys will move the current cell alone. The rows or cells can be selected or deselected by pressing the Space key.

this.sfDataGrid1.SelectionMode = GridSelectionMode.Multiple;
Me.sfDataGrid1.SelectionMode = GridSelectionMode.Multiple

The following image shows for multiple mode row selection.
Windows forms datagrid showing multiple mode row selection

The following image shows for multiple mode cell selection.

Windows forms datagrid showing multiple mode cell selection

Disable the selection

The selection can be disabled by setting the SelectionMode property as None.

this.sfDataGrid1.SelectionMode = GridSelectionMode.None;
Me.sfDataGrid1.SelectionMode = GridSelectionMode.None

Selection on a particular row can be disabled by handling the CurrentCellActivating event. FilterRow and AddNewRow cells can be edited and selected even though the AllowFocus property is set to false.

The column selection and navigation can be disabled by setting the AllowFocus property to false.

// Disable the focus for the column.
sfDataGrid.Columns[2].AllowFocus = false;
' Disable the focus for the particular column.
sfDataGrid.Columns(2).AllowFocus = False

NOTE

You cannot select the header rows and table summary rows of SfDataGrid. You cannot also select the unbound rows which are above and below the table summary row.

CheckBox column selection

SfDataGrid allows you to select or deselect rows by interacting with the check box in a column. All the rows in a datagrid can be selected by interacting with an intuitive check box in the column header. Refer to GridCheckBoxSelectorColumn documentation for more information.

Get selected rows and cells

The SelectedItem property returns the data object of the selected row and the SelectedIndex property returns the index of the SelectedItem in SfDataGrid. SelectedItem denotes the first selected row in multiple selection.

Row selection

Get all the selected records using the SelectedItems property.

Cell selection

Get the selected cells using the GetSelectedCells method of CellSelectionController collection.

CurrentItem vs SelectedItem

Both SelectedItem and CurrentItem returns the same data object when there is single row is selected in SfDataGrid. When more than one rows are selected, the record that had been selected initially is maintained in SelectedItem and the record that currently have focus is maintained in CurrentItem.

Programmatic selection

Process selection using properties

A single row can be selected by setting the SelectedItem or SelectedIndex property.

var record = SelectionHelper.GetRecordAtRowIndex(this.sfDataGrid, 3);
this.sfDataGrid1.SelectedItem = record;
Dim record = SelectionHelper.GetRecordAtRowIndex(Me.sfDataGrid, 3)
Me.sfDataGrid1.SelectedItem = record
var recordIndex = this.sfDataGrid.TableControl.ResolveToRecordIndex(5);
this.sfDataGrid1.SelectedIndex = recordIndex;
Dim recordIndex = Me.sfDataGrid.TableControl.ResolveToRecordIndex(5)
Me.sfDataGrid1.SelectedIndex = recordIndex

A single cell can be selected by using the SelectCell method.

var record = this.sfDataGrid.View.Records[5];
var column = this.sfDataGrid.Columns[2];
this.sfDataGrid.SelectCell(record, column);
Dim record = Me.sfDataGrid.View.Records(5)
Dim column = Me.sfDataGrid.Columns(2)
Me.sfDataGrid.SelectCell(record, column)

Multiple rows can be selected by adding data objects to SelectedItems property.

var records = this.sfDataGrid.View.Records;

foreach(var record in records)
{
    var obj = record.Data as OrderInfo;
    if (obj.ProductName == "Raclette Courdavault")
      this.sfDataGrid1.SelectedItems.Add(obj);
}
Dim records = Me.sfDataGrid.View.Records

For Each record In records
	Dim obj = TryCast(record.Data, OrderInfo)
	If obj.ProductName = "Raclette Courdavault" Then
	  Me.sfDataGrid1.SelectedItems.Add(obj)
	End If
Next record

Windows forms datagrid showing programmatic selection

Process Selection using Methods

SfDataGrid Allows to select a range of rows through SelectRows method.

this.sfDataGrid1.SelectRows(3, 6);
Me.sfDataGrid1.SelectRows(3, 6)

Windows forms datagrid showing programmatic range of rows selection

SfDataGrid allows you to select a range of cells through the SelectCells method.

this.sfDataGrid.SelectCells(sfDataGrid.View.Records[5], sfDataGrid.Columns["ProductName"], sfDataGrid.View.Records[10], sfDataGrid.Columns["Quantity"]);
Me.sfDataGrid.SelectCells(sfDataGrid.View.Records(5), sfDataGrid.Columns("ProductName"), sfDataGrid.View.Records(10), sfDataGrid.Columns("Quantity"))

Windows forms datagrid showing programmatic range of cells selection

All the rows or cells can be selected by using SelectAll method in SfDataGrid.

this.sfDataGrid1.SelectAll();
Me.sfDataGrid1.SelectAll()

Process Current Cell

When a particular record is assigned to the CurrentItem property, the CurrentCell will be moved to corresponding record when the SelectionMode is Multiple or Extended and the selection will added to the particular record item when the SelectionMode is Single.

this.sfDataGrid1.CurrentItem = SelectionHelper.GetRecordAtRowIndex(this.sfDataGrid, 2);
Me.sfDataGrid1.CurrentItem = SelectionHelper.GetRecordAtRowIndex(Me.sfDataGrid, 2)

The CurrentCell can be moved to a particular RowColumnIndex by using the MoveToCurrentCell method.

this.sfDataGrid1.MoveToCurrentCell(new RowColumnIndex(3, 3));
Me.sfDataGrid1.MoveToCurrentCell(New RowColumnIndex(3, 3))

Get the current cell

The current cell information such as row index, column index, and column name can be retrieved using the SfDataGrid.CurrentCell property.

if (this.sfDataGrid.CurrentCell != null)
{
    var currentCellRowIndex = this.sfDataGrid.CurrentCell.RowIndex;
    var currentCellColumnIndex = this.sfDataGrid.CurrentCell.ColumnIndex;
    var currentCellColumn = this.sfDataGrid.CurrentCell.Column;
}
If Me.sfDataGrid.CurrentCell IsNot Nothing Then
	Dim currentCellRowIndex = Me.sfDataGrid.CurrentCell.RowIndex
	Dim currentCellColumnIndex = Me.sfDataGrid.CurrentCell.ColumnIndex
	Dim currentCellColumn = Me.sfDataGrid.CurrentCell.Column
End If

Getting currentcell information in windows form datagrid

Clear Selection

The Selection can be cleared by using the ClearSelection Method. Selection can also be removed by setting null toSelectionItem or by clearing the SelectedItems property.

this.sfDataGrid1.ClearSelection();
Me.sfDataGrid1.ClearSelection()

SfDataGrid can clear the selection of a particular cell by using the UnSelectCell method.

var removeRecord = this.sfDataGrid.View.Records[7];
var removeColumn = this.sfDataGrid.Columns[3];
this.sfDataGrid.UnselectCell(removeRecord, removeColumn);
Dim removeRecord = Me.sfDataGrid.View.Records(7)
Dim removeColumn = Me.sfDataGrid.Columns(3)
Me.sfDataGrid.UnselectCell(removeRecord, removeColumn)

Clearing selected cell in windows forms datagrid

SfDataGrid can clear the selection of a group of cells by using the UnSelectCells method.

var firstRecord = this.sfDataGrid.View.Records[7];
var lastRecord = this.sfDataGrid.View.Records[8];
var firstColumn = this.sfDataGrid.Columns[2];
var lastColumn = this.sfDataGrid.Columns[3];
this.sfDataGrid.UnselectCells(firstRecord, firstColumn, lastRecord, lastColumn);
Dim firstRecord = Me.sfDataGrid.View.Records(7)
Dim lastRecord = Me.sfDataGrid.View.Records(8)
Dim firstColumn = Me.sfDataGrid.Columns(2)
Dim lastColumn = Me.sfDataGrid.Columns(3)
Me.sfDataGrid.UnselectCells(firstRecord, firstColumn, lastRecord, lastColumn)

Clearing selected cells in windows forms datagrid

Get the Cell Value

Get the current cell value

The current cell value can be retrieved by using the GridCellRendererBase.GetControlValue method when the CurrentCell value is not null.

if (sfDataGrid1.CurrentCell != null)
{
    // Get the CurrentCellValue
    var currentCellValue = sfDataGrid1.CurrentCell.CellRenderer.GetControlValue();
    MessageBox.Show(currentCellValue.ToString(), "Current Cell Value");
}
If sfDataGrid1.CurrentCell IsNot Nothing Then
	' Get the CurrentCellValue
	Dim currentCellValue = sfDataGrid1.CurrentCell.CellRenderer.GetControlValue()
	MessageBox.Show(currentCellValue.ToString(), "Current Cell Value")
End If

Getting currentcell value in windows forms datagrid

Get the value of a cell

A particular cell value can be retrieved from records in the SfDataGrid.View by using the row column index of the cell.

// Get the cell value for RowIndex = 5 and ColumnIndex = 2
string cellValue;
int rowIndex = 5;
int columnIndex = sfDataGrid1.TableControl.ResolveToGridVisibleColumnIndex(2);
if (columnIndex < 0)
    return;
var mappingName = sfDataGrid1.Columns[columnIndex].MappingName;
var recordIndex = sfDataGrid1.TableControl.ResolveToRecordIndex(rowIndex);
if (recordIndex < 0)
    return;
if (sfDataGrid1.View.TopLevelGroup != null)
{
    var record = sfDataGrid1.View.TopLevelGroup.DisplayElements[recordIndex];
    if (!record.IsRecords)
        return;
    var data = (record as RecordEntry).Data;
    cellValue = (data.GetType().GetProperty(mappingName).GetValue(data, null).ToString());
}
else
{
    var record1 = sfDataGrid1.View.Records.GetItemAt(recordIndex);
    cellValue = (record1.GetType().GetProperty(mappingName).GetValue(record1, null).ToString());
}

MessageBox.Show(cellValue, "Value in cell (" + rowIndex + ", " + columnIndex + ")");
Dim cellValue As String
Dim rowIndex As Integer = 5
Dim columnIndex As Integer = sfDataGrid1.TableControl.ResolveToGridVisibleColumnIndex(2)
If columnIndex < 0 Then
	Return
End If
Dim mappingName = sfDataGrid1.Columns(columnIndex).MappingName
Dim recordIndex = sfDataGrid1.TableControl.ResolveToRecordIndex(rowIndex)
If recordIndex < 0 Then
	Return
End If
If sfDataGrid1.View.TopLevelGroup IsNot Nothing Then
	Dim record = sfDataGrid1.View.TopLevelGroup.DisplayElements(recordIndex)
	If Not record.IsRecords Then
		Return
	End If
	Dim data = (TryCast(record, RecordEntry)).Data
	cellValue = (data.GetType().GetProperty(mappingName).GetValue(data, Nothing).ToString())
Else
	Dim record1 = sfDataGrid1.View.Records.GetItemAt(recordIndex)
	cellValue = (record1.GetType().GetProperty(mappingName).GetValue(record1, Nothing).ToString())
End If

MessageBox.Show(cellValue, "Value in cell (" & rowIndex & ", " & columnIndex & ")")
& ")")

Getting cell value in windows forms datagrid

Getting the cell value by using cell click event

The cell value can also be retrieved by using the SfDataGrid.CellClick event when clicking the cell.

this.sfDataGrid.CellClick += OnSfDataGridCellClick;   

private void OnSfDataGridCellClick(object sender, CellClickEventArgs e)
{
    // Get the row index value        
    var rowIndex = e.DataRow.RowIndex;
    //Get the column index value
    var columnIndex = e.DataColumn.ColumnIndex;
    //Get the cell value            
    var cellValue = this.sfDataGrid.View.GetPropertyAccessProvider().GetValue(e.DataRow.RowData, e.DataColumn.GridColumn.MappingName);
    MessageBox.Show("Cell Value \t:    " + cellValue + "\n" + "Row Index \t:    " + rowIndex + "\n" + "Column Index \t:    " + columnIndex, "Cell Value");
}
AddHandler sfDataGrid1.CellClick, AddressOf OnSfDataGridCellClick 

Private Sub OnSfDataGridCellClick(ByVal sender As Object, ByVal e As CellClickEventArgs)
		 ' Get the row index value        
		 Dim rowIndex = e.DataRow.RowIndex
		 'Get the column index value
		 Dim columnIndex = e.DataColumn.ColumnIndex
		 'Get the cell value            
		 Dim cellValue = Me.sfDataGrid.View.GetPropertyAccessProvider().GetValue(e.DataRow.RowData, e.DataColumn.GridColumn.MappingName)
		 MessageBox.Show("Cell Value " & Constants.vbTab & ":    " & cellValue + Constants.vbLf & "Row Index " & Constants.vbTab & ":    " & rowIndex + Constants.vbLf & "Column Index " & Constants.vbTab & ":    " & columnIndex, "Cell Value")
End Sub

Retrieving cell value by clicking in windows forms datagrid

Scrolling Rows

Automatic Scrolling on Drag Selection

SfDataGrid will scrolls rows and columns automatically while performing the drag selection like excel.

Mouse and Keyboard Behaviors

Keyboard Behavior

Key or KeyCombinations        

Description

DownArrow Moves CurrentCell directly below the active current cell. If the CurrentCell is in last row, pressing Down arrow does nothing.
UpArrow         Moves the CurrentCell directly above the active current cell. If the CurrentCell is in first row, pressing Up arrow does nothing.
LeftArrow         Moves the current cell previous to the active current cell. If the CurrentCell is in first cell, pressing Left arrow does nothing. If the focused row is group header, the group will be collapsed when it is in expanded state.
RightArrow Moves the current cell to next to the active current cell. If the CurrentCell is in last cell, pressing Right arrow does nothing. If the focused row is group header, the group will be expanded when it is in collapsed state.
Home / Ctrl + LeftArrow         Moves the current cell to the first cell of the current row.
End / Ctrl + RightArrow Moves the current cell to the last cell of the current row.
PageDown         The SfDataGrid will be scrolled to next set of rows that are not displayed in view, including the row that are partially displayed and the current cell is set to last row.
PageUp         The SfDataGrid will be scrolled to previous set of rows that are not displayed in view, including the row that are partially displayed and the current cell is set to the first row.
Tab Moves the current cell to next to the active current cell. If the active current cell is the last cell of the current row, the focus will moved to first cell of the row next to the current row.If the active current cell is the last cell of the last row, the focus will be moved to next control in the tab order of the parent container.
Shift + Tab Moves the current cell previous to the active current cell. If the active current cell is the first cell of the current row, the current cell will moved to last cell of the row previous to the current row.If the active current cell is the first cell of the first row, the focus will be moved to previous control in the tab order of the parent container.
Ctrl + DownArrow Moves the current cell to the current column of the last row.
Ctrl + UpArrow Moves the current cell to the current column of the first row.
Ctrl + Home Moves the current cell to the first cell of the first row.
Ctrl + End Moves the current cell to the last cell of the last row.
Enter If the active current cell is in edit mode, the changes will committed and moves the current cell to below the active current cell. If the active current cell is in last row, commits changes only and retains in the same cell.
Ctrl + Enter Commits only the changes when the current cell in edit mode and retains the focus in same cell.
F2 If the DataGrid.AllowEditing property is true and the GridColumn.AllowEditing property is true for the current column, the current cell enters into edit mode.
Esc If the current cell is in edit mode, reverts the changes that had been done in the current cell. If the underlying source implements the IEditableObject.
Delete         If the current cell is not in edit mode, the current row will be deleted.
Ctrl + A         All rows or cells will be selected.

Shift Key Combinations

When the SelectionMode is set to Extended, multiple rows can be selected by using the navigation keys along with the Shift key. Before navigation starts, the current cell will be marked as a pressed cell and the selection will be done in all rows between the pressed cell and current cell.

Key Combinations

Shift + DownArrow
Shift + UpArrow
Shift + RightArrow
Shift + LeftArrow
Shift + Home
Shift + End
Shift + PageDown
Shift + PageUp
Shift + Ctrl + DownArrow
Shift + Ctrl + UpArrow
Shift + Ctrl + RightArrow
Shift + Ctrl + LeftArrow
Shift + Ctrl + Home
Shift + Ctrl + End
Shift + Ctrl + PageDown
Shift + Ctrl + PageUp

Mouse Behavior

The selection can be enabled/disabled when the mouse button is in pressed state by setting the AllowSelectionOnMouseDown property.
When a row is clicked along with Shift key, all the rows between the pressed cell to the current cell will be selected, if the SelectionMode is set to Extended.

Customization Using Events

Cancel CurrentCell Moving

The current cell moving process can be canceled within CurrentCellActivating event by setting CurrentCellActivatingEventArgs.Cancel as true.

void SfDataGrid1_CurrentCellActivating(object sender, CurrentCellActivatingEventArgs e)
{
  if((e.DataRow.RowData as OrderInfo).CustomerID == "FRANS")
  {
     e.Cancel = true;
  }
}
Private Sub SfDataGrid1_CurrentCellActivating(ByVal sender As Object, ByVal e As CurrentCellActivatingEventArgs)
  If (TryCast(e.DataRow.RowData, OrderInfo)).CustomerID = "FRANS" Then
	 e.Cancel = True
  End If
End Sub

Customizing Selection Behavior

Select all the default rows

By default, SelectAll method is select all the rows (CaptionSummary, GroupSummary, UnboundRows, FilterRow, AddNewRow and DefaultRow) in SfDataGrid. The following code shows how to select all the default row except other rows by using SelectAll method.

//Using SelectAll method.
private void SelectAll(object sender, EventArgs e)
{
    this.sfDataGrid.SelectAll();
    this.sfDataGrid.SelectedNodeEntries.Clear();
}
' Using SelectAll event.
private void SelectAll(Object sender, EventArgs e)
	Me.sfDataGrid.SelectAll()
	Me.sfDataGrid.SelectedNodeEntries.Clear()

By default, select all the rows (CaptionSummary, GroupSummary, UnboundRows, FilterRow, AddNewRow and DefaultRow) when press the Ctrl+A key in SfDataGrid. The following code shows how to select all the default row except other rows by overriding the HandleKeyOperations method in RowSelectionController.

//Using the Custom SelectionController.
sfDataGrid.SelectionController = new CustomSelectionController(this.sfDataGrid);

public class CustomSelectionController : RowSelectionController
{
    SfDataGrid sfDataGrid;

    public CustomSelectionController(SfDataGrid sfDataGrid)
        : base(sfDataGrid)
    {
        this.sfDataGrid = sfDataGrid;
    }

    protected override void HandleKeyOperations(KeyEventArgs args)
    {
        base.HandleKeyOperations(args);
        if ((Control.ModifierKeys == Keys.Control || Control.ModifierKeys == Keys.ControlKey
            || Control.ModifierKeys == Keys.LControlKey || Control.ModifierKeys == Keys.RControlKey) && args.KeyCode == Keys.A)
            this.sfDataGrid.SelectedNodeEntries.Clear();
    }
}
'Using the Custom SelectionController.
sfDataGrid.SelectionController = New CustomSelectionController(Me.sfDataGrid)
public class CustomSelectionController : RowSelectionController
	Dim sfDataGrid As SfDataGrid

	public CustomSelectionController(SfDataGrid sfDataGrid)
		MyBase.New(sfDataGrid)
		Me.sfDataGrid = sfDataGrid

	protected override void HandleKeyOperations(KeyEventArgs args)
		MyBase.HandleKeyOperations(args)
		If (Control.ModifierKeys = Keys.Control OrElse Control.ModifierKeys = Keys.ControlKey OrElse Control.ModifierKeys = Keys.LControlKey OrElse Control.ModifierKeys = Keys.RControlKey) AndAlso args.KeyCode = Keys.A Then
			Me.sfDataGrid.SelectedNodeEntries.Clear()
		End If

Selection using custom selection controller in windows forms datagrid

Samples Link: SelectAllRows

Change Enter key behavior

When pressing the Enter key, the current cell will be moved to the next focused row of the same column, by default. The following code shows how to change the Enter key behavior by overriding the HandleKeyOperations method in RowSelectionController.

sfDataGrid.SelectionController = new CustomSelectionController(this.sfDataGrid);

public class CustomSelectionController : RowSelectionController
{
    public CustomSelectionController(SfDataGrid dataGrid)
        : base(dataGrid)
    {
    }

    protected override void HandleKeyOperations(KeyEventArgs args)
    {
        if (args.KeyCode == Keys.Enter)
            return;

        base.HandleKeyOperations(args);
    }
}
sfDataGrid.SelectionController = New CustomSelectionController(Me.sfDataGrid)

public class CustomSelectionController : RowSelectionController
	public CustomSelectionController(SfDataGrid dataGrid)
		MyBase.New(dataGrid)

	protected override void HandleKeyOperations(KeyEventArgs args)
		If args.KeyCode = Keys.Enter Then
			Return
		End If

		MyBase.HandleKeyOperations(args)

Tab key navigation

The current cell navigation can be disabled in Tab key using the AllowStandardTab property. If AllowStandardTab is enabled, then the focus will be moved to next control in tab order;if else, the current cell will be moved to next cell in order in DataGrid.

this.sfDataGrid1.AllowStandardTab = true;
Me.sfDataGrid1.AllowStandardTab = True

Displaying Message Box on Current Cell Activated

The CurrentCellActivated event provides notification when the current cell is moved from one cell to another.

this.sfDataGrid1.CurrentCellActivated += SfDataGrid1_CurrentCellActivated;

void SfDataGrid1_CurrentCellActivated(object sender, CurrentCellActivatedEventArgs e)
{
    MessageBox.Show("The current cell is moved to the (" + e.DataRow.RowIndex + "," + e.DataColumn.ColumnIndex + ")");
}
AddHandler sfDataGrid1.CurrentCellActivated, AddressOf SfDataGrid1_CurrentCellActivated

Private Sub SfDataGrid1_CurrentCellActivated(ByVal sender As Object, ByVal e As CurrentCellActivatedEventArgs)
	MessageBox.Show("The current cell is moved to the (" & e.DataRow.RowIndex & "," & e.DataColumn.ColumnIndex & ")")
End Sub

Cancel Selection

The selection process can be canceled within SelectionChanging event by setting the SelectionChangingEventArgs.Cancel property as true.

void SfDataGrid1_SelectionChanging(object sender, SelectionChangingEventArgs e)
{
   if (e.RemovedItems.Count != 0)
       e.Cancel = true;
}
Private Sub SfDataGrid1_SelectionChanging(ByVal sender As Object, ByVal e As SelectionChangingEventArgs)
   If e.RemovedItems.Count <> 0 Then
	   e.Cancel = True
   End If
End Sub

Displaying Message Box on Selection Changed

The SelectionChanged event provides notification when the selection is changed from one row to another.

this.sfDataGrid1.SelectionChanged += SfDataGrid1_SelectionChanged;
void SfDataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    MessageBox.Show("Selection has been changed");
}
AddHandler sfDataGrid1.SelectionChanged, AddressOf SfDataGrid1_SelectionChanged
Private Sub SfDataGrid1_SelectionChanged(ByVal sender As Object, ByVal e As SelectionChangedEventArgs)
	MessageBox.Show("Selection has been changed")
End Sub

Retrieving the Current Item and Display in Message Box

The current item can be displayed in a message box by using the CurrentItem property in the SfDataGrid.SelectionChanged event.

this.sfDataGrid1.SelectionChanged += sfDataGrid1_SelectionChanged;

void sfDataGrid1_SelectionChanged(object sender, Syncfusion.WinForms.DataGrid.Events.SelectionChangedEventArgs e)
{
    var orderInfo = this.sfDataGrid.CurrentItem as OrderInfo;
    MessageBox.Show("\n Order ID \t-  " + orderInfo.OrderID.ToString() +
                    "\n Customer ID \t-  " + orderInfo.CustomerID +
                    "\n Product Name \t-  " + orderInfo.ProductName +
                    "\n Order Date \t-  " + orderInfo.OrderDate +
                    "\n Quantity \t-  " + orderInfo.Quantity +
                    "\n Unit Price \t-  " + orderInfo.UnitPrice, "Order Details");
}
AddHandler sfDataGrid1.SelectionChanged, AddressOf SfDataGrid1_SelectionChanged

Private Sub sfDataGrid1_SelectionChanged(ByVal sender As Object, ByVal e As Syncfusion.WinForms.DataGrid.Events.SelectionChangedEventArgs)
	Dim orderInfo = TryCast(Me.sfDataGrid.CurrentItem, OrderInfo)
    MessageBox.Show(Constants.vbLf & " Order ID " & Constants.vbTab & "-  " & orderInfo.OrderID.ToString() &
                    Constants.vbLf & " Customer ID " & Constants.vbTab & "-  " & orderInfo.CustomerID +
                    Constants.vbLf & " Product Name " & Constants.vbTab & "-  " & orderInfo.ProductName +
                    Constants.vbLf & " Order Date " & Constants.vbTab & "-  " & orderInfo.OrderDate.ToString() &
                    Constants.vbLf & " Quantity " & Constants.vbTab & "-  " & orderInfo.Quantity.ToString() &
                    Constants.vbLf & " Unit Price " & Constants.vbTab & "-  " & orderInfo.UnitPrice.ToString(), "Order Details")
End Sub

![Retrieving current row information by clicking in windows forms datagrid

Appearance

SfDataGrid allows to customize the appearance of the selected rows and current cell through SfDatagrid.Style property.

Selection

Change the Background and Foreground Color for Selection

The selection background and foreground color can be changed of by SfDataGrid.Style.SelectionStyle property.

this.sfDataGrid1.Style.SelectionStyle.BackColor = Color.LightSeaGreen;
this.sfDataGrid1.Style.SelectionStyle.TextColor = Color.DarkBlue;
Me.sfDataGrid1.Style.SelectionStyle.BackColor = Color.LightSeaGreen
Me.sfDataGrid1.Style.SelectionStyle.TextColor = Color.DarkBlue

Selection appearance customization in Windows forms datagrid

CurrentCell

Change the Background, Foreground, BorderColor, and BorderThickness of CurrentCell

The Background, Foreground, BorderColor, and BorderThickness of the current cell can be changed by SfDataGrid.Style.CurrentCellStyle property.

this.sfDataGrid1.Style.CurrentCellStyle.BackColor = SystemColors.Highlight;
this.sfDataGrid1.Style.CurrentCellStyle.TextColor = Color.White;
this.sfDataGrid1.Style.CurrentCellStyle.BorderColor = Color.Red;
this.sfDataGrid1.Style.CurrentCellStyle.BorderThickness = GridBorderWeight.Thick;
Me.sfDataGrid1.Style.CurrentCellStyle.BackColor = SystemColors.Highlight
Me.sfDataGrid1.Style.CurrentCellStyle.TextColor = Color.White
Me.sfDataGrid1.Style.CurrentCellStyle.BorderColor = Color.Red
Me.sfDataGrid1.Style.CurrentCellStyle.BorderThickness = GridBorderWeight.Thick

Currentcell appearance customization in Windows forms datagrid

See also

How to select the entire column in WinForms DataGrid (SfDataGrid)

How to change the Enter key behavior in WinForms DataGrid (SfDataGrid)

How to skip selection for summary rows in WinForms DataGrid (SfDataGrid)

How to search and select record in WinForms DataGrid (SfDataGrid)

How to scroll to a specific record programmatically in WinForms DataGrid (SfDataGrid)