我正在研究一个C#程序,现在我有一个Form和几个类.我希望能够从我的课程中访问一些Form控件(例如a TextBox).当我尝试更改TextBox我的类中的文本时,我收到以下错误:
非静态字段,方法或属性'Project.Form1.txtLog'需要对象引用
如何访问Form1.cs其中一个类中的方法和控件?
Jam*_*rue 29
您正在尝试访问该类而不是该对象.这个陈述对于初学者来说可能会让人感到困惑,但是你有效地试图通过拿起房子计划的大门打开你的房门.
如果您确实想直接从类(您没有)访问表单组件,则可以使用实例化表单的变量.
根据您想要的方式,您可以更好地将控件文本或其他任何内容发送到类中的方法,例如
public void DoSomethingWithText(string formText)
{
// do something text in here
}
Run Code Online (Sandbox Code Playgroud)
或者在表单类上公开属性并在其中设置表单文本 - 例如
string SomeProperty
{
get
{
return textBox1.Text;
}
set
{
textBox1.Text = value;
}
}
Run Code Online (Sandbox Code Playgroud)
Tim*_*ter 14
另一种解决方案是将文本框(或您想要修改的控件)传递给将其作为参数进行操作的方法.
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";
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
111352 次 |
| 最近记录: |