如何从 C# 中的类访问表单方法和控件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/217389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 18:31:55  来源:igfitidea点击:

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

c#winforms

提问by user13504

I'm working on a C# program, and right now I have one Formand a couple of classes. I would like to be able to access some of the Formcontrols (such as a TextBox) from my class. When I try to change the text in the TextBoxfrom my class I get the following error:

我正在开发一个 C# 程序,现在我有一个Form和几个类。我希望能够从我的班级访问一些Form控件(例如 a TextBox)。当我尝试更改TextBox班级中的文本时,出现以下错误:

An object reference is required for the non-static field, method, or property 'Project.Form1.txtLog'

非静态字段、方法或属性“Project.Form1.txtLog”需要对象引用

How can I access methods and controls that are in Form1.csfrom one of my classes?

如何访问Form1.cs我的一个类中的方法和控件?

采纳答案by JamesSugrue

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;
   }
}

回答by Steven A. Lowe

  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
  1. 您必须引用表单对象才能访问其元素
  2. 元素必须被声明为 public 以便另一个类可以访问它们
  3. 不要这样做——你的班级必须对你的表单是如何实现的了解太多;不要在表单类之外公开表单控件
  4. 相反,在您的表单上创建公共属性以获取/设置您感兴趣的值
  5. 发布更多关于您想要什么以及为什么的详细信息,听起来您可能正朝着与良好封装实践不一致的方向前进

回答by Keith Nicholas

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"

回答by rp.

You need to make the members in the for the form class either public or, if the service class is in the same assembly, internal. Windows controls' visibility can be controlled through their Modifiers properties.

您需要将表单类中的成员设为公共成员,或者如果服务类在同一程序集中,则设为内部成员。Windows 控件的可见性可以通过它们的 Modifiers 属性来控制。

Note that it's generally considered a bad practice to explicitly tie a service class to a UI class. Rather you should create good interfaces between the service class and the form class. That said, for learning or just generally messing around, the earth won't spin off its axis if you expose form members for service classes.

请注意,将服务类显式绑定到 UI 类通常被认为是一种不好的做法。相反,您应该在服务类和表单类之间创建良好的接口。也就是说,对于学习或一般来说,如果您为服务类公开表单成员,地球将不会偏离其轴。

rp

转速

回答by Timothy Carter

Another solution would be to pass the textbox (or control you want to modify) into the method that will manipulate it as a parameter.

另一种解决方案是将文本框(或您要修改的控件)传递到将其作为参数进行操作的方法中。

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

    private void button1_Click(object sender, EventArgs e)
    {
        TestClass test = new TestClass();
        test.ModifyText(textBox1);
    }
}

public class TestClass
{
    public void ModifyText(TextBox textBox)
    {
        textBox.Text = "New text";
    }
}

回答by Ojhnny777

If the form starts up first, in the form Load handler we can instantiate a copy of our class. We can have properties that reference whichever controls we want to reference. Pass the reference to the form 'this' to the constructor for the class.

如果表单首先启动,在表单加载处理程序中,我们可以实例化我们的类的副本。我们可以拥有引用我们想要引用的任何控件的属性。将对表单“this”的引用传递给类的构造函数。

public partial class Form1 : Form
{
    public ListView Lv
    {
        get { return lvProcesses; }
    }

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Utilities ut = new Utilities(this);
    }
}

In your class, the reference from the form is passed into the constructor and stored as a private member. This form reference can be used to access the form's properties.

在您的类中,来自表单的引用被传递到构造函数并存储为私有成员。此表单引用可用于访问表单的属性。

class Utilities
{
    private Form1 _mainForm;
    public Utilities(Form1 mainForm)
    {
        _mainForm = mainForm;
        _mainForm.Lv.Items.Clear();
    }
}

回答by Jim

I'm relatively new to c# and brand new to stackoverflow. Anyway, regarding the question on how to access controls on a form from a class: I just used the ControlCollection (Controls) class of the form.

我对 c# 比较陌生,对 stackoverflow 是全新的。无论如何,关于如何从类访问表单上的控件的问题:我只是使用了表单的 ControlCollection (Controls) 类。

        //Add a new form called frmEditData to project.
        //Draw a textbox on it named txtTest; set the text to
        //something in design as a test.
        Form frmED =  new frmEditData();
        MessageBox.Show(frmED.Controls["txtTest"].Text);

Worked for me, maybe it will be of assistance in both questions.

为我工作,也许对这两个问题都有帮助。

回答by Toprak

JUST YOU CAN SEND FORM TO CLASS LIKE THIS

只是你可以发送表格到这样的班级

Class1 excell = new Class1 (); //you must declare this in form as you want to control

excel.get_data_from_excel(this); // And create instance for class and sen this form to another class

INSIDE CLASS AS YOU CREATE CLASS1

在创建 CLASS1 时进入内部类

class Class1
{
    public void get_data_from_excel (Form1 form) //you getting the form here and you can control as you want
    {
        form.ComboBox1.text = "try it"; //you can chance Form1 UI elements inside the class now
    }
}

IMPORTANT : But you must not forgat you have declare modifier form properties as PUBLIC and you can access other wise you can not see the control in form from class

重要提示:但是你不能忘记你已经将修饰符表单属性声明为 PUBLIC 并且你可以访问其他明智的你不能从类中看到表单中的控件