Search code examples
c#vb.netprojects

Calling a C# from a VB project in one solution


I have 2 projects in one solution.

The main is a VB.net project and the secondary is a C# project. I want to call a form from the C# project from the VB.net project at the click of a button but I am unsure how.

I have read it is possible if I create the C# .dll and reference it but I cannot find a guide for this. Would anybody give me a step by step on how one would accomplish this please?


Solution

  • It's a fairly simple and easy thing to do, and also common. Saves duplicating code across projects if you have multiple projects which all have a function which does the same thing.

    1. Right Click the VB project and click Add -> Reference...
    2. Press the Projects node on the left.
    3. Now hover over the C# project and click the checkbox that appears.

    You've now added the reference. Beware that you cannot then reference the Vb project from the C# as Visual Studio will not allow this because you're creating a circular reference.

    To call a form to show up, you can do the following.

    First, you'll need to make a reference somewhere of the new form. For example; (OtherProject being the name of the other project, and FormName being the name of the form in the project. Depending on what you're doing, you might want to do this when you start your VB app, or you might only need it once. It entirely depends on your setup.

    Dim OtherProjectForm as New OtherProject.FormName 
    

    When you've done that, just go ahead and do

    OtherProjectForm.Show()
    

    or of course, again, depending what you're doing,

    OtherProjectForm.ShowDialog()
    

    You'll also be able to access and public members of the form. By default, every control on the form's access mode is "Friend", which means just objects which are part of the same assembly can access them, but if you need to, you can make them public. Or you can just make methods to interact with them.