如果我按下Button1,则表格2->'Hello'中的textBox1
如果我再按一次button2以显示form2,则“ Hello”一词消失,原始Textbox1的文本也会出现。
如何防止按button1的结果消失?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2(this);
frm2.textBox1.Text = "Hello";
frm2.Show();
}
private void Button2_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2(this);
frm2.Show();
}
}
public partial class Form2 : Form
{
Form1 frm1 = new Form1();
public Form2(Form1 _form)
{
InitializeComponent();
frm1 = _form;
}
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
答案 0 :(得分:1)
尝试在按钮单击事件之外创建Form2实例。
~
答案 1 :(得分:0)
如果要保留先前在Form2
中设置的文本,则不允许关闭Form2
。为防止Form2
关闭,请在e.Cancel = true;
事件处理程序中设置FormClosing
:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true; // Clancel closing
Visible = false; // Instead, make Form2 invisible.
}
}
确保在表单设计器中创建事件处理程序。单独复制/粘贴将无法接通事件。
Form1
的代码:
public partial class Form1 : Form
{
private Form2 _frm2 = new Form2();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
_frm2.textBox1.Text = "Hello";
_frm2.Show();
}
private void button2_Click(object sender, EventArgs e)
{
_frm2.Show();
}
}
但是可能我们看错了方向。我们不应该使用文本框来存储数据。相反,我们为此目的创建一个数据类。现在,我们可以自由地打开和关闭表格。剩下的只是数据。
public class Data
{
public string Greeting { get; set; }
}
Form2
代码:
private readonly Data _data;
public Form2(Data data) // Note that now, we pass a Data object, not a Form
{
InitializeComponent();
_data = data;
textBox1.Text = _data.Greeting;
}
private void TextBox1_TextChanged(object sender, EventArgs e)
{
_data.Greeting = textBox1.Text; // Stores back text box edits to the Data object.
}
Form1
代码:
private readonly Data _data = new Data();
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
_data.Greeting = "Hello";
var frm2 = new Form2(_data);
frm2.Show();
}
private void Button2_Click(object sender, EventArgs e)
{
var frm2 = new Form2(_data);
frm2.Show();
}