how to cast COM object type to Excel.Checkbox type

2.3k Views Asked by At

I am adding a checkbox to excel and i have issue casting a COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Excel.CheckBox', any help would be appreciated! I am working on web app using visual studio 2008 and office 2007. The error happens at this line :- chkBx = (Microsoft.Office.Interop.Excel.CheckBox)obj;

Microsoft.Office.Interop.Excel.OLEObjects objs = (Microsoft.Office.Interop.Excel.OLEObjects)mWSheet1.OLEObjects(System.Reflection.Missing.Value);

Microsoft.Office.Interop.Excel.OLEObject obj = objs.Add("Forms.CheckBox.1",
            System.Reflection.Missing.Value,
            System.Reflection.Missing.Value,
            false,
            false,
            System.Reflection.Missing.Value,
            System.Reflection.Missing.Value,
            234,
            234,
            108,
            21);

            Microsoft.Office.Interop.Excel.CheckBox chkBx;
            chkBx = (Microsoft.Office.Interop.Excel.CheckBox)obj;
            chkBx.Value = true;
            chkBx.Caption = "xyz";
1

There are 1 best solutions below

1
On

It looks to me like you can't cast it because it simply doesn't implement that interface. You can check if a System.__ComObject supports an interface without casting, and consequently throwing an exception, by using the as operator as described here: HOW TO: Check the Type of a COM Object (System.__ComObject) with Visual C# .NET.

I wonder if you are using the wrong method to add the checkbox to a worksheet. Isn't the more common method to go through Microsoft.Office.Tools.Excel.ControlCollection as described here: Adding Controls to Office Documents at Run Time.

If you used ControlCollection, I think your code would end up looking something like this:

private void AddCheckBox()
{
    Worksheet vstoWorksheet = Globals.Factory.GetVstoObject(
        this.Application.ActiveWorkbook.Worksheets[1]);
    System.Windows.Forms.CheckBox checkbox = 
        new System.Windows.Forms.CheckBox();
    checkbox.Checked = true;
    checkbox.Text = "xyz"   
    vstoWorksheet.Controls.AddControl(234, 234, 108, 21, "checkbox1");
}