简体   繁体   中英

C# Access function in another Form Class

i start my programm with a form called "mainWindow" in this form i have a button and this run a function that open a new form as object. my problem is i cant access a control on this object or a function on this object and i dont understand why

the first form:

public partial class mainWindow : Form
{
    public mainWindow()
    {
        InitializeComponent();
        this.drawDriverGrid();
    }

    public void drawDriverGrid() 
    {
        Form driverGridForm = new driverGridView();
        driverGridForm.GetSelected();
    }

this is the second form

public partial class driverGridView : Form 
{
    public driverGridView() 
    {
        InitializeComponent();
    }

    public int GetSelected() 
    {
        return 1;
    }
}

i cant run the GetSelected function

The compiler must be informed (HA HA) that you intend to use a method of driverGridView. So NOT:

    Form driverGridForm = new driverGridView();
    driverGridForm.GetSelected();

By saying "Form" in the declaration of driverGridForm you are saying "I only wish to use methods of Form with this variable".

Rather, you intended to say "I wish to use methods of driverGridView with this variable", so:

    driverGridView driverGridForm = new driverGridView();
    driverGridForm.GetSelected();

Or, better:

    var driverGridForm = new driverGridView();
    driverGridForm.GetSelected();

which means "let the compiler deduce from the new expression what type I meant here".

Note also that C# naming conventions are that class names and namespace names and method names start with a capital, so it should be

    var driverGridForm = new DriverGridView();
    driverGridForm.GetSelected();

and it should be namespace Test and so on.

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