New to Telerik UI for WinFormsStart a free 30-day trial

How to Access RadSpreadsheet's Editor

Updated over 6 months ago

Environment

Product VersionProductAuthor
2021.1.122RadSpreadsheet for WinFormsDesislava Yordanova

Description

This article demonstrates how to access the RadSpreadsheet's editor and handle the user's input while editing a cell.

The required references are listed below:

  • Telerik.WinControls
  • Telerik.WinControls.UI
  • TelerikCommon
  • Telerik.WinControls.RadSpreadsheet
  • Telerik.Windows.Documents.Core
  • Telerik.Windows.Documents.Spreadsheet

Solution

The editor can be detected via the Selection property that the SpreadsheetElement.ActiveWorksheetEditor offers. It triggers the ActiveCellModeChanged event when the selected cell enters edit mode. By default, a Microsoft RichTextBox is hosted inside the editor:

C#
private Telerik.WinForms.Controls.Spreadsheet.Worksheets.RadWorksheetEditor activeEditor;
private NormalWorksheetEditorPresenter activePresenter;

public Form1()
{
    InitializeComponent();

    this.radSpreadsheet1.SpreadsheetElement.ActiveSheetEditorChanged += SpreadsheetElement_ActiveSheetEditorChanged;
    InitializeSubscription();
}

public void InitializeSubscription()
{
    this.activeEditor = this.radSpreadsheet1.SpreadsheetElement.ActiveWorksheetEditor;
    this.activePresenter = this.activeEditor.ActivePresenter as NormalWorksheetEditorPresenter;

    this.activeEditor.Selection.ActiveCellModeChanged -= Selection_ActiveCellModeChanged;
    this.activeEditor.ActivePresenterChanged -= activeEditor_ActivePresenterChanged;

    this.activeEditor.Selection.ActiveCellModeChanged += Selection_ActiveCellModeChanged;
    this.activeEditor.ActivePresenterChanged += activeEditor_ActivePresenterChanged;
}

void SpreadsheetElement_ActiveSheetEditorChanged(object sender, EventArgs e)
{
    InitializeSubscription();
}

void activeEditor_ActivePresenterChanged(object sender, EventArgs e)
{
    this.activePresenter = this.activeEditor.ActivePresenter as NormalWorksheetEditorPresenter;
}

void Selection_ActiveCellModeChanged(object sender, EventArgs e)
{
    if (activeEditor.Selection.ActiveCellMode == Telerik.WinForms.Controls.Spreadsheet.Worksheets.ActiveCellMode.Edit)
    {
        CellInputUILayer uiLayer = this.activePresenter.UILayers.GetByName(WorksheetPredefinedUILayers.CellInput) as CellInputUILayer;
        CellEditor cellEditor = uiLayer.ActiveCellEditor as CellEditor;
        if (cellEditor != null)
        {
            RadHostItem editorHost = cellEditor.Children.First() as RadHostItem;
            if (editorHost != null)
            {
                RichTextBox rtb = editorHost.HostedControl as RichTextBox;
                rtb.KeyDown -= rtb_KeyDown;
                rtb.KeyDown += rtb_KeyDown;
            }
        }
    }
}

private void rtb_KeyDown(object sender, KeyEventArgs e)
{
    Console.WriteLine(e.KeyCode);
}
  

See Also