Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access methods in ThisAddin.cs file

Tags:

c#

excel

vsto

I have created an Excel Addin project in C#. Now the solution contains a file ThisAddin.cs, which has a class ThisAddin. Later I have added an item called Form to the same solution. In Form, when I click on a button, for that button click event i want to call a method inside ThisAddin.cs file.

namespace ExcelAddIn
{
    public partial class ThisAddIn
    {
        public void RefreshExcelData()
        {
        }
    }
}

Now in MyForm.cs, while trying to create an object for ThisAddin class there is a compilation error that Thisaddin class doesn't have a constructor that takes 0 arguments.

private void btnUploadTestCases_Click(object sender, EventArgs e)
{
    ThisAddIn objrefresh = new ThisAddin();
}

What am I missing here?

like image 825
krrishna Avatar asked Dec 05 '22 14:12

krrishna


2 Answers

You are approaching the problem from the wrong direction. When you click the button, you don't want to create a new add-in, what you really want is to access the add-in instance which is created for you by VSTO when Excel starts up, which is accessible via Globals.ThisAddIn.

Change your code in the Form to the following:

private void btnUploadTestCases_Click(object sender, EventArgs e)
{
    var addIn = Globals.ThisAddIn;
    addIn.RefreshExcelData();           
}

... and it should work a charm.

That being said, is there a good reason for this a method to be on ThisAddIn? In general, ThisAddIn should be used to wire up and tear down the add-in when Excel starts up / shuts down, and I would recommend to put as little logic in there as possible.

like image 194
Mathias Avatar answered Dec 10 '22 10:12

Mathias


Use this code:

Globals.ThisAddIn.Application.StatusBar = "Referesh clicked!!!."; Globals.ThisAddIn.RefreshExcelData();

Just make sure your function remains public.

like image 22
SutharMonil Avatar answered Dec 10 '22 10:12

SutharMonil