Search code examples
c#user-interfacemonolabelgtk2

How to update the label in MainWindow from controller class?


My controller is a main method which implement my model and do the calculations. My MainWindow class has one button and it will update the result from my controller once it clicked. Now I have problem regrading how to update labels from my controller.

Button method is my view

public void Button1_Clicked(object sender, EventArgs args)
    {

 }

I try to access MainWindow class from my controller class

            Application.Init();
            MainWindow win = new MainWindow();
            //here I want to use win object to access my view
            //but I can not access my labels

            win.Show();
            Application.Run();

The strange part is:

win.Button1_Clicked.first_label 

I only can access label through my button which is totally not make any sense to me


Solution

  • If you want to update the labels or any other control in the form, you should write a corresponding method with a public modifier.

    Making labels/controls public is a bad practice.

    Therefore, my suggested solution would be to write a public method with, e.g. a string argument to set the text;

    e.g.:

    public void SetLabelText(string text)
    {
        LabelResult.Text = text;
    }
    

    EDIT:

    to set the text use

    win.SetLabelText("some text");