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?
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.
Use this code:
Globals.ThisAddIn.Application.StatusBar = "Referesh clicked!!!."; Globals.ThisAddIn.RefreshExcelData();
Just make sure your function remains public
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With