C#WindowsForms - 在visual studio上从form1发送文本框到form2

时间:2013-04-25 17:58:06

标签: c# visual-studio textbox send

我在visual studio上有2个表单,

form1 have textbox1.text
form2, have textbox2.text and btnSave
当我点击表格1上的另一个按钮时,

obs:form2打开:

Form new = new form2();
           nova.Show();

如何将text2的内容从form2发送到form1(textbox1)点击btnSave? 在此单击按钮事件中需要什么代码。

谢谢

3 个答案:

答案 0 :(得分:3)

请试试这个: 第1步:为form2类创建一个构造函数,如下所示:

 public Form2(string strTextBox)
        {
            InitializeComponent();
            label1.Text = strTextBox;
        }

步骤2:在form1的按钮单击事件处理程序中实例化form2类,如下所示:

 private void button1_Click(object sender, EventArgs e)
        {
            Form2 obj1 = new Form2(textBox1.Text);
            obj1.Show();
            this.Hide();
        }

答案 1 :(得分:1)

在第二个表单上创建一个事件,可以在保存表单时触发:

public event Action Saved;

然后在该表单上创建一个允许访问文本框文本的属性:

public string SomeTextValue //TODO: rename to meaningful name
    { get{ return textbox2.Text;} }

然后,您需要在保存表单时触发Saved事件:

if(Saved != null)
    Saved();

然后,当您首次在Form1中创建表单时,将事件处理程序附加到该事件:

Form2 child = new Form2();
child.Saved += () => textbox1.Text = child.SomeTextValue;
child.Show();

请注意,如果您在保存时关闭第二个表单,那么您不需要自定义事件,只需使用FormClosing即可。

答案 2 :(得分:0)

研究我能够使它工作,失去了几个小时,但现在一切都很完美,这是适合我的代码:

在form2上:

public partial class form2 : Form
    {
        private string nome;
        public string passvalue
        {
            get { return nome; }
            set { nome = value; }
        }

form2,按钮保存:

private void btnSalvar_Click(object sender, EventArgs e)
        {
            passvalue = txtMetragemcubica.Text;
            this.Hide();
        }
form1上的

(此按钮打开form2):

private void btnMetragemcubica_Click(object sender, EventArgs e)
        {
            form2 n = new form2();
            n.ShowDialog();
            txtMetragem.Text = n.passvalue
        }

现在它以这种方式工作:在表单1上打开,然后我点击按钮btnMetragemcubica和form2打开,然后我在不同的文本框上插入值并在txtMetragemcubica上得到结果,当我点击保存按钮(btnSalvar)时它关闭form2和将值发送到txtMetragem文本框中的form1。

在这里工作完美,希望也帮助其他人。 无论如何,谢谢你的帮助