Search code examples
c#spreadsheetgear

Select a shape programmatically


How to programmatically (C#) select a shape (or chart) in SpreadsheetGear?

I have tried:

1. IShape.select(false); // failed
2. ShapeSelection = ...; // failed

Solution

  • IShape.Select(...) is the correct API needed to select a shape. I do see you passed in false for the "replace" parameter, which means you are adding this new shape to any other shapes that were already selected (i.e., IWorksheetWindowInfo.ShapeSelection.Count will be 2 or greater). If you want to replace the current shape selection you would need to pass in true instead.

    Below is some sample code that demonstrates selecting one or more shapes on a sheet and verifies this behavior with some Console.WriteLine(...)'s, but I also verified this behavior when viewing these actions on SpreadsheetGear's WorkbookView UI control:

    // Create a workbook and a couple shapes on the active worksheet.
    IWorkbook workbook = Factory.GetWorkbook();
    IWorksheet worksheet = workbook.ActiveWorksheet;
    IShape shape1 = worksheet.Shapes.AddShape(AutoShapeType.Rectangle, 5, 5, 50, 50);
    IShape shape2 = worksheet.Shapes.AddShape(AutoShapeType.Oval, 75, 57, 50, 50);
    
    // Ensure no shapes are selected.
    IShapeRange shapeSelection = worksheet.WindowInfo.ShapeSelection;
    Console.WriteLine($"ShapeSelection is null? {shapeSelection == null}");
    // OUTPUT: ShapeSelection is null? True
    
    // Select shape1 ("Rectangle 1")
    shape1.Select(true);
    shapeSelection = worksheet.WindowInfo.ShapeSelection;
    Console.WriteLine($"ShapeSelection: Count={shapeSelection.Count}, Name[0]={shapeSelection[0].Name}");
    // OUTPUT: ShapeSelection: Count=1, Name[0]=Rectangle 1
    
    // Select shape2 ("Oval 2")
    shape2.Select(true);
    shapeSelection = worksheet.WindowInfo.ShapeSelection;
    Console.WriteLine($"ShapeSelection: Count={shapeSelection.Count}, Name[0]={shapeSelection[0].Name}");
    // OUTPUT: ShapeSelection: Count=1, Name[0]=Oval 2
    
    // Select both shapes (false passed into IShape.Select(...))
    shape1.Select(false);
    shapeSelection = worksheet.WindowInfo.ShapeSelection;
    Console.WriteLine($"ShapeSelection: Count={shapeSelection.Count}, Name[0]={shapeSelection[0].Name}, Name[1]={shapeSelection[1].Name}");
    // OUTPUT: ShapeSelection: Count=2, Name[0]=Oval 2, Name[1]=Rectangle 1