Skip to main content

How to: Replace Built-In Command with a Custom Command

  • 2 minutes to read

This example illustrates the technique used to modify the functionality of the existing SpreadsheetControl command used to clear the contents of the selected cell.

The SpreadsheetControl exposes the ISpreadsheetCommandFactoryService interface that enables you to substitute the default command with your own custom command.

You have to create a custom command class, inherited from the command that you wish to replace. In this example, it is the DevExpress.XtraSpreadsheet.Commands.FormatClearContentsCommand class. Override the ExecuteCore method to specify actions performed by a command when it is executed.

View Example

public class CustomFormatClearContentsCommand : FormatClearContentsCommand {
    public CustomFormatClearContentsCommand(ISpreadsheetControl control)
        : base(control) {

    protected override void ExecuteCore() {
        MessageBox.Show("Custom command executed");

Create a class inherited from the SpreadsheetCommandFactoryServiceWrapper. This class will replace the default command service. In this class, you should override the CreateCommand method to create an instance of a custom command class. An identifier of the currently processed command is passed as a parameter to this method.

View Example

public class CustomService : SpreadsheetCommandFactoryServiceWrapper {
    public CustomService(ISpreadsheetCommandFactoryService service)
        : base(service) {
    public SpreadsheetControl Control {get;set;}

    public override SpreadsheetCommand CreateCommand(SpreadsheetCommandId id)
        if (id == SpreadsheetCommandId.FormatClearContents || id == SpreadsheetCommandId.FormatClearContentsContextMenuItem)
            return new CustomFormatClearContentsCommand(Control);

        return base.CreateCommand(id);


Use the SpreadsheetCommandFactoryServiceWrapper class descendant to substitute the default command service obtained using the SpreadsheetControl.GetService<T> method.

View Example

private void SubstituteService() {
    ISpreadsheetCommandFactoryService service = (ISpreadsheetCommandFactoryService)spreadsheetControl1.GetService(typeof(ISpreadsheetCommandFactoryService));
    CustomService customService = new CustomService(service);
    customService.Control = spreadsheetControl1;

Now, instead of clearing the contents of the selected cell, you will get the message “Custom command executed”.