简体   繁体   中英

Converting line of code from VB to C#

I am trying to convert a block of code from VB to C# but am running into an issue w/ one line of code.

VB Code:

Dim tsAV As System.Windows.Forms.ToolStrip = 
    CType(objHost.FormMain.Controls("tsMain"), Windows.Forms.ToolStrip)

Code I have in C#:

System.Windows.Forms.ToolStrip tsAV = 
    (System.Windows.Forms.ToolStrip)objHost.FormMain;

My problem comes in on the FormMain method. When I use VB code I can get the Controls method but in C# I cannot. I use the same Interface DLL included both ways.

Am I doing something wrong? Is it possible for a DLL to include certain things that only work in VB?

You should be able to use this as your C# code:

// using System.Windows.Forms;
ToolStrip tsAV = (ToolStrip)objHost.FormMain().Controls["tsMain"];
                                            ^^^^^^^^^^^^^^^^^^^

In your example you are trying to cast the Form as a ToolStrip , that won't work.

If you are trying to retrieve a ToolStrip in ac# Form, you can use the following code. This assumes that the ToolStrip name is "tsAV" and that you are executing this code from a method within FormMain (which is presumably the class name of the main form).

using System.Windows.Forms;
...
ToolStrip tsAV = (ToolStrip)Controls["tsMain"];

From outside of the form, you can find the ToolStrip by using the following code:

using System.Windows.Forms;
...
FormMain form = new FormMain();
ToolStrip tsAV = (ToolStrip)form.Controls["tsMain"];

Update: Assuming that objHost is a controller of sorts and FormMain is a field or property name that returns an instance of a form, rather than a class name, you can use the following:

using System.Windows.Forms;
...
ToolStrip tsAV = (ToolStrip)objHost.FormMain.Controls["tsMain"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM