question

JaimeStuardo-7580 avatar image
0 Votes"
JaimeStuardo-7580 asked TimonYang-MSFT commented

Worksheet.SelectionChange get lost after some time

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

dotnet-csharpoffice-excel-itprooffice-vsto-com-dev
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

TimonYang-MSFT avatar image
0 Votes"
TimonYang-MSFT answered TimonYang-MSFT commented

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.

· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Yes! that was the problem. I was calling Add method of workbook inside the method. That way, a locally defined worksheet object was created. I guess that object was disposed when no more activity in the worksheet. I created a class scope worksgeet variable and it worked.

Regards
Jaime

0 Votes 0 ·

anonymous usertuardo-7580
I am glad to hear that.
Have a wonderful day.

0 Votes 0 ·