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

时间:2021-09-27 15:53:58

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 (such as a TextBox) from my class. When I try to change the text in the TextBox from my class I get the following error:

我正在开发一个C#程序,现在我有一个Form和几个类。我希望能够从我的类中访问一些Form控件(例如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.cs from one of my classes?

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

8 个解决方案

#1


28  

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

#2


14  

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

#3


9  

  1. you have to have a reference to the form object in order to access its elements
  2. 您必须具有对表单对象的引用才能访问其元素

  3. the elements have to be declared public in order for another class to access them
  4. 必须将元素声明为public才能让另一个类访问它们

  5. 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
  6. 不要这样做 - 你的班级必须过多地了解你的表格是如何实现的;不要在表单类之外公开表单控件

  7. instead, make public properties on your form to get/set the values you are interested in
  8. 相反,在表单上创建公共属性以获取/设置您感兴趣的值

  9. 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
  10. 发布您想要的更多细节以及为什么,听起来您可能正朝着与良好封装实践不一致的方向前进

#4


3  

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"

#5


2  

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.

如果表单首先启动,在表单Load处理器中我们可以实例化我们类的副本。我们可以拥有引用我们想要引用的控件的属性。将对“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();
    }
}

#6


1  

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.

您需要使表单类中的成员为public,或者,如果服务类位于同一程序集中,则为internal。 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

#7


1  

I'm relatively new to c# and brand new to *. 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#的新手,也是*的新手。无论如何,关于如何从类访问表单上的控件的问题:我只是使用了表单的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.

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

#8


0  

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

INSIDE CLASS,因为你创建了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而你可以访问其他方面你无法从类中看到控件的形式

#1


28  

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

#2


14  

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

#3


9  

  1. you have to have a reference to the form object in order to access its elements
  2. 您必须具有对表单对象的引用才能访问其元素

  3. the elements have to be declared public in order for another class to access them
  4. 必须将元素声明为public才能让另一个类访问它们

  5. 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
  6. 不要这样做 - 你的班级必须过多地了解你的表格是如何实现的;不要在表单类之外公开表单控件

  7. instead, make public properties on your form to get/set the values you are interested in
  8. 相反,在表单上创建公共属性以获取/设置您感兴趣的值

  9. 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
  10. 发布您想要的更多细节以及为什么,听起来您可能正朝着与良好封装实践不一致的方向前进

#4


3  

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"

#5


2  

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.

如果表单首先启动,在表单Load处理器中我们可以实例化我们类的副本。我们可以拥有引用我们想要引用的控件的属性。将对“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();
    }
}

#6


1  

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.

您需要使表单类中的成员为public,或者,如果服务类位于同一程序集中,则为internal。 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

#7


1  

I'm relatively new to c# and brand new to *. 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#的新手,也是*的新手。无论如何,关于如何从类访问表单上的控件的问题:我只是使用了表单的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.

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

#8


0  

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

INSIDE CLASS,因为你创建了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而你可以访问其他方面你无法从类中看到控件的形式