【发布时间】:2012-11-26 00:55:13
【问题描述】:
我在 form1 上有一个文本框。
我想要做的是将文本框的值从 form1 获取到 form2 中。
我该怎么做?
【问题讨论】:
我在 form1 上有一个文本框。
我想要做的是将文本框的值从 form1 获取到 form2 中。
我该怎么做?
【问题讨论】:
我所做的是创建一个新项目并添加第二个表单,然后向两个表单添加一个文本框,并在 Form1 上使用一个按钮将其文本框的值推送到 Form2。
为此,请在 Form2 上创建一个属性并从 Form1 设置它。像这样:
Form1
public partial class Form1 : Form
{
Form2 frm2;
public Form1()
{
InitializeComponent();
frm2 = new Form2();
frm2.Show(this);
}
private void button1_Click(object sender, EventArgs e)
{
frm2.ModifyTextBoxValue = textBox1.Text;
}
}
Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string ModifyTextBoxValue
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
}
通过这种方式,如果需要,也可以使用相同的属性从 Form2 中提取数据。
【讨论】:
你可以使用 .Tag 属性(看看我的问题here 简单的方法是这样的: 在 form2 中添加另一个文本框
在表格 1 中执行此操作。此代码会将 texBox.text 存储在 form1 中
try
{
private void change_Click(object sender, EventArgs e)
{
form1 frm1 = new form();
frm1.Tag = this.textBox1.text;
frm1.ShowDialog();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
然后在加载 form2 时写下这个。此代码将 texBox2 的值替换为 texBox1 的值
string myText = (string)this.Tag;
this.textBox2.text = myText;
【讨论】: