I have been trying to add a combobox or really any form controls to an excel sheet that was created on the fly. I was able to add a combobox to an excel sheet when creating an Excel Workbook project in c# and was able to access Controls.AddComboBox function in the document level (Sheet1) as so: Fig 1
namespace ExcelWorkbook2{
public partial class Sheet1{
private void Sheet1_Startup(object sender, System.EventArgs e){
Microsoft.Office.Tools.Excel.Controls.ComboBox comboBox1
=this.Controls.AddComboBox(this.Range["A1", "A1"], "comboBox1");
comboBox1.Items.Add("1 Item");
this
refers to sheet1
This code works fine when creating a workbook project but when I am creating an excel sheet on the fly like so:
Fig 2
Application xlApp = new Application();
xlApp.Visible = true;
Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet ws = (Worksheet)wb.Worksheets[1];
I am not able to go into the WorkSheet (ws) and get "controls.AddCombobox." Putting the worksheet (Fig 2) in the quickwatch says that System.___Comobject the "this" object in the other project (Fig 1) returns the value (ExcelWorkbook2.Sheet1). How can I be able to get to the Controls.AddCombobox which is casted as WorkSheetBase to use in the c# generated worksheet (Fig 2). Thanks
Controls.AddCombobox is only available to the Host Items of the Microsoft.Office.Tools.Excel Namespace. In your case, Sheet1 is a host item that is created at design-time.
Worksheets created at run-time..
To create a ComboBox on a worksheet at run-time that handles events in C# and avoid VBA:
Assembly References:
Microsoft.Vbe.Interop (Microsoft.Vbe.Interop.dll)
Microsoft.Vbe.Interop.Forms (Microsoft.Vbe.Interop.Forms.dll)
Microsoft.VisualBasic (Microsoft.VisualBasic.dll)
Tested / Working Code:
To create a Button on a worksheet at run-time that handles events in C# and avoid VBA
Please support with your votes and comments. Thanks, Leo.