Worksheet.SelectionChange get lost after some time

Jaime Stuardo 51 Reputation points
2021-04-23T23:06:12.037+00:00

Hello,

In a VSTO addin for Excel, developed in C#, I am creating a sheet this way:

public void Populate(List<Systems.Models.Producto> productos)
{
    Excel.Workbook workbook = _excelApp.ActiveWorkbook;
    Excel.Worksheet worksheet = workbook.Sheets.Add(After: workbook.Sheets[workbook.Sheets.Count]);
    worksheet.SelectionChange += Worksheet_SelectionChange;
    worksheet.Name = "Inventario";
    // More instructions
}

Well... I have noticed that Worksheet_SelectionChange is called for a moment when I select any cell in the sheet. After a few minutes later, that event is not called anymore.

At first, I thought that the object that owns the method populate was being disposed. That could sound strange since this object owns the sheet also so that while the sheet is not closed, the object will be alive. However, just in case, I have declared the object that owns the method populate globally to the parent object, but the same problem occurs.

Any help will be appreciated. Thanks

Jaime

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,197 questions
Office Development
Office Development
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Development: The process of researching, productizing, and refining new or existing technologies.
3,456 questions
Excel Management
Excel Management
Excel: A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.Management: The act or process of organizing, handling, directing or controlling something.
1,638 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Timon Yang-MSFT 9,571 Reputation points
    2021-04-26T08:34:09.03+00:00

    anonymous usertuardo-7580
    I couldn't reproduce this error, I put it there for about ten minutes and tested it again and the event was still triggered correctly.
    The biggest possibility is that the object is released by the garbage collector.Try to set Excel.Application, Excel.Workbook, Excel.Worksheet as global variables to see if it is useful.