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

前端 未结 8 1034
轮回少年
轮回少年 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 08:19
    1. you have to have a reference to the form object in order to access its elements
    2. the elements have to be declared public in order for another class to access them
    3. don't do this - your class has to know too much about how your form is implemented; do not expose form controls outside of the form class
    4. instead, make public properties on your form to get/set the values you are interested in
    5. post more details of what you want and why, it sounds like you may be heading off in a direction that is not consistent with good encapsulation practices
    0 讨论(0)
  • 2020-11-30 08:24

    You need access to the object.... you can't simply ask the form class....

    eg...

    you would of done some thing like

    Form1.txtLog.Text = "blah"
    

    instead of

    Form1 blah = new Form1();
    blah.txtLog.Text = "hello"
    
    0 讨论(0)
提交回复
热议问题