当我添加文本时,C#.Net属性(GET,SET)返回空白



嗨,这是我在谷歌上呆了好几个小时后的第二天。我有一个表单和一个类,其中最重的代码是,在表单中我有一些复选框和文本框,当类程序基于checkboxex运行时,代码将只运行部分代码。但是,如果我尝试返回复选框,它只返回false,或者如果我尝试文本框,它仅返回空白,如果我勾选文本框或如果我向文本框添加文本。

namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("Lading");
this.textBox1.Text = "THIS IS TXT.1";
this.textBox2.Text = "THIS IS TXT.2";
this.checkBox1.Checked = true;
this.checkBox2.Checked = true;
}
private void button1_Click(object sender, EventArgs e)
{
Work_.Work wrk = new Work_.Work();
wrk.Testing();
}
private string result1;
public string test1
{
get { return result1 = this.textBox1.Text; }
set { }
}
private string result2;
public string test2
{
get { return result2 = this.checkBox1.Checked.ToString(); }
set { }
}
}
}

以及类文件(它被添加到"工作"文件夹中(

namespace WinFormsApp1.Work_
{
class Work
{
public void Testing()
{
Form1 form = new Form1();
string Return = form.test1;
MessageBox.Show(Return);
string Return2 = form.test2;
MessageBox.Show(Return2);
}
}
}

这个属性定义可能不是您想要的:

private string result1;
public string test1
{
get { return result1 = this.textBox1.Text; }
set { }
}

这将用textBox的内容更新变量result1并返回它。这里根本不需要该变量。只需将属性简化为

public string test1
{
get { this.textBox1.Text; }
}

然而,实际的问题是,如果不显示对话框,Form1_Load方法永远不会执行。在Form1 form = new Form1();之后插入form.ShowDialog()

Work类中,您正在创建一个新的Form,因此访问它不会给您原始表单中的值。一种方法是将表单传递给Work类,如下所示:

private void button1_Click(object sender, EventArgs e)
{
Work_.Work wrk = new Work_.Work();
wrk.Testing(this);
}

Work类中:

public void Testing(Form1 form)
{
string Return = form.test1;
MessageBox.Show(Return);
string Return2 = form.test2;
MessageBox.Show(Return2);
}

最新更新