Вопрос

I'm having a hard time understanding referencing and calls. If a form already exists, how can I call a method from it without using re-creating the form? (Using the new operator).

i.e. Menu_View Menu = Menu.SetMenuView();

Currently my scope flows a bit like this:

In the Menu:

    public Menu_View()
    {
        // Initialises the Menu form.
        // Runs the method in the controller to open the Login form.
        InitializeComponent();  
        User_Controller UserController = new User_Controller();              
        UserController.Show_Login(this);
    }

In the Controller:

    public void Show_Login(Menu_View Main_Menu)
    {
        // Creates an object of the User_LoginView.
        // Set the Parent Form of the Child window
        // Display the new form.
        User_LoginView LoginView = new User_LoginView(); 
        LoginView.MdiParent = Main_Menu; 
        LoginView.Show();
    }

In the Login Form:

public partial class User_LoginView : Form
{
    // Opens the form.
    // When the Login Button is clicked, runs checks and comparisons.
    public User_LoginView()
    {
        InitializeComponent();
    }

    public void btnLogin_Click(object sender, EventArgs e)
    {
        User_Controller.Check_Login(this);
    }    

Then back in the Controller:

public static void Compare_Login(User_LoginView LoginView)
    {
        // Compares the returned AccessLevel. 
        // if it is corect; closes the Login and runs the SetMenuView method,
        // if it is incorrect; shows an error.
        if (AccessModel.AccessLevel > 0)
        {
            Console.WriteLine("Access Level " + AccessModel.AccessLevel);
            LoginView.Close();
            Menu_View.accessLevelSet = AccessModel.AccessLevel;
        }
        else
        {
            ErrorCodes_Controller LoginError = new ErrorCodes_Controller();
            LoginError.WrongLoginError();
        }
        // This line gives me an error.
        Menu_View Menu = Menu.SetMenuView();
    }
Это было полезно?

Решение

In order to do this you need to pass around the created instance as parameters or fields to the methods and types that need access to the value. For instance here you could just add a field to User_LoginView of type Menu_View.

class User_LoginView : Form
{
  public Menu_View Menu_View;

  ...
}

This could be set when creating the instance

User_LoginView LoginView = new User_LoginView();
LoginView.Menu_View = Main_Menu;

And then accessed in Compare_Login

// This line gives me an error.
LoginView.Menu_View.SetMenuView();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top