如何从C#中的类访问表单方法和控件?
我正在开发一个C#程序,现在我有一个Form
和几个类。 我希望能够从我的类中访问一些Form
控件(例如TextBox
)。 当我尝试从我的类更改TextBox
中的TextBox
,我收到以下错误:
非静态字段,方法或属性’Project.Form1.txtLog’需要对象引用
如何从我的一个类中访问Form1.cs
方法和控件?
您正在尝试访问该类而不是该对象。 这个陈述对于初学者来说可能会让人感到困惑,但是你有效地试图通过打开房屋计划的大门打开你的房门。
如果您确实想直接从类(您没有)访问表单组件,您将使用实例化表单的变量。
根据您想要的方式,您可以更好地将控件文本或其他任何内容发送到类中的方法,例如
public void DoSomethingWithText(string formText) { // do something text in here }
或者在表单类上公开属性并在其中设置表单文本 – 例如
string SomeProperty { get { return textBox1.Text; } set { textBox1.Text = value; } }
另一种解决方案是将文本框(或您想要修改的控件)传递给将其作为参数进行操作的方法。
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"; } }
- 您必须具有对表单对象的引用才能访问其元素
- 必须将元素声明为public才能让另一个类访问它们
- 不要这样做 – 你的class级必须过多地了解你的表格是如何实现的; 不要在表单类之外公开表单控件
- 相反,在表单上创建公共属性以获取/设置您感兴趣的值
- 发布您想要的更多细节以及为什么,听起来您可能正朝着与良好封装实践不一致的方向前进
您需要访问该对象….您不能简单地询问表单类….
例如…
你会做一些像这样的事情
Form1.txtLog.Text = "blah"
代替
Form1 blah = new Form1(); blah.txtLog.Text = "hello"
如果表单首先启动,在表单Load处理器中我们可以实例化我们类的副本。 我们可以拥有引用我们想要引用的控件的属性。 将对“this”forms的引用传递给类的构造函数。
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); } }
在您的类中,表单中的引用将传递给构造函数并存储为私有成员。 此表单引用可用于访问表单的属性。
class Utilities { private Form1 _mainForm; public Utilities(Form1 mainForm) { _mainForm = mainForm; _mainForm.Lv.Items.Clear(); } }
您需要使表单类中的成员为public,或者,如果服务类位于同一程序集中,则为internal。 Windows控件的可见性可以通过其Modifiers属性进行控制。
请注意,将服务类显式绑定到UI类通常被认为是一种不好的做法。 相反,您应该在服务类和表单类之间创建良好的接口。 也就是说,为了学习或者只是乱搞,如果你公开服务类的表单成员,地球就不会脱离它的轴。
RP
我是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);
为我工作,也许这对两个问题都有帮助。
只是你可以发送表格类似这样的类别
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,因为你创建了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 } }
重要提示:但是你不能忘记你已经将声明修饰符表单属性声明为PUBLIC而你可以访问其他方面你无法从类中看到控件的forms