How to: Obtain Selected Range and Active Cell
- 2 minutes to read
To access a range of cells in a worksheet (e.g., to format, merge, insert or delete cells), an end-user selects this range. You can programmatically get or set the selected cell range using the SpreadsheetControl.Selection or Worksheet.Selection property. Another way to select the cell range is to use the range’s RangeExtensions.Select extension method, defined by the RangeExtensions class. This extension method is accessible as a method of the CellRange object and called by using the instance method syntax.
One of the cells within a range selected by an end-user is the active cell. When an end-user types something, data is inserted into this cell. Usually, the active cell is the top left cell in the selected range. However, it can be any cell within the current selection. End-users can specify the position of the active cell by pressing TAB, SHIFT+TAB, ENTER or SHIFT+ENTER. To specify the active cell in code, use the SpreadsheetControl.ActiveCell, SpreadsheetControl.SelectedCell or Worksheet.SelectedCell property.
An end-user can also select multiple non-adjacent cells or cell ranges in the worksheet simultaneously by holding down the CTRL key when selecting cell ranges. To get or set the list of selected ranges in code, use the SpreadsheetControl.GetSelectedRanges/SpreadsheetControl.SetSelectedRanges or Worksheet.GetSelectedRanges/Worksheet.SetSelectedRanges methods. If there is more than one range selected in the worksheet, the Selection property returns the range that contains the active cell (e.g., E3:F7 in the image below).
The SpreadsheetControl object’s members mentioned above provide access to cell selection and the active cell in the active worksheet. To manage cell selection in any other worksheet, use members of the corresponding Worksheet object. The following example demonstrates how to set borders around cell ranges currently selected by an end-user, and apply a color to the active cell.
using System.Collections.Generic;
using DevExpress.Spreadsheet;
// ...
private void button1_Click(object sender, EventArgs e) {
spreadsheetControl1.SelectedCell.FillColor = Color.LightGray;
IList<CellRange> currentSelection = spreadsheetControl1.GetSelectedRanges();
foreach (CellRange range in currentSelection) {
Formatting rangeFormatting = range.BeginUpdateFormatting();
range.Borders.SetOutsideBorders(Color.Green, BorderLineStyle.MediumDashDot);
range.EndUpdateFormatting(rangeFormatting);
}
}
The SpreadsheetControl.SelectionChanged event occurs each time an end-user selects cells in an active worksheet.