How to access form methods and controls from a class in C#?

前端 未结 8 1079
轮回少年
轮回少年 2020-11-30 07:52

I\'m working on a C# program, and right now I have one Form and a couple of classes. I would like to be able to access some of the Form controls (s

8条回答
  •  一整个雨季
    2020-11-30 07:59

    You are trying to access the class as opposed to the object. That statement can be confusing to beginners, but you are effectively trying to open your house door by picking up the door on your house plans.

    If you actually wanted to access the form components directly from a class (which you don't) you would use the variable that instantiates your form.

    Depending on which way you want to go you'd be better of either sending the text of a control or whatever to a method in your classes eg

    public void DoSomethingWithText(string formText)
    {
       // do something text in here
    }
    

    or exposing properties on your form class and setting the form text in there - eg

    string SomeProperty
    {
       get 
       {
          return textBox1.Text;
       }
       set
       {
          textBox1.Text = value;
       }
    }
    

提交回复
热议问题