[RESOLVED] [1.0/1.1] Late Bind - Convert VB.NET to C#
I am late binding Excel in my app and I need to fix a few errors. I have the app instance created fine but I need to access other properties and methods of it and I get errors saying "some method is not defined for object".
Thanks
VB Code:
object oWB = moApp.[u]Workbooks[/u].Add();
oWB.[u]Sheets[/u]("Sheet1").Cells(1, 1).Value = "Meow!";
Re: [1.0/1.1] Late Bind - Convert VB.NET to C#
I still havent got the first posts code but I am making progress on these parts but still having trouble converting.
VB Code:
private object moApp;
private System.Type moAppType;
/// Create the late bound app object
moAppType = System.Type.GetTypeFromProgID("Excel.Application");
object moApp = System.Activator.CreateInstance(moAppType);
/// ...
/// Closing of form but this line wont work for late binding
if ((moApp.Workbooks.Count) > 0)
/// So I converted it to this but not working
if (moAppType.InvokeMember("Workbooks.Count", System.Reflection.BindingFlags.GetProperty, null, moApp, null) > 0)
[Error: Operator '>' cannot be applied to operands of type 'object' and 'int']
Re: [1.0/1.1] Late Bind - Convert VB.NET to C#
Woot! I got another error fixed.
The moApp.Workbooks.Add() method converts to late binding in this way.
VB Code:
[color=dimgray]///[/color] [color=darkgreen]Original C# code:[/color]
moApp.Workbooks.[color=black]Add[/color]();
[color=dimgray]///[/color] [color=darkgreen]Converted to late binding:[/color]
moAppType.InvokeMember("Workbooks.Add", System.Reflection.BindingFlags.[b]InvokeMethod[/b], [color=blue]null[/color], moApp, [color=blue]null[/color]);
I cant test it yet as I have a couple of more errors but it compiles.
I guess you can call child members without drilling down the object heirachy?
MS on System.Type.InvokeMember
Re: [1.0/1.1] Late Bind - Convert VB.NET to C#
This should work:
if (System.Convert.ToInt32(moAppType.InvokeMember("Workbooks.Count", System.Reflection.BindingFlags.GetProperty, null, moApp, null)) > 0)
Re: [RESOLVED] [1.0/1.1] Late Bind - Convert VB.NET to C#
I found that I can not reference the property without transversing the object heirarchy first. I got around getting the count property this way. :)
VB Code:
if (System.Convert.ToInt32(oWBs.GetType().InvokeMember("Count", BindingFlags.InvokeMethod | BindingFlags.GetProperty, null, oWBs, null)) > 0)
Still was hung up on the casting though as I am still learning C#.
Thanks David :thumb: