Cher Cher - 7 months ago 28
C# Question

how to pass a form as a parameter?

First I know there are already answer for this question but most solution seems complicated for nothing.

Situation :

I have a form called frm1. I want to pass it as parameter

myfunc(ref frm1)


I would then do

private void myfunc(ref Form frm1)

It says : frm1 is a type but is used as a variable.


My reason for doing this is because depending on choice I pass my form to one of either two functions which fills it differently.

Problem :

However I cannot pass as argument my form. However I can pass other controls like button in the same way. How can I do this simply with the form, without interface etc...

Answer Source

There is something wrong with the way you are passing the parameter in. Are you definitely passing in the instance and not the type?

Here's a working example.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        this.Name = "form";

        Form f = this;

        doSomethingWithForm(f);
    }

    private void doSomethingWithForm(Form f)
    {
        Console.WriteLine(f.Name);
    }
}