从父窗体和子窗体传递参数值

本文关键字:窗体 参数 | 更新日期: 2023-09-27 18:11:48

我有两个表单,一个带有'Add'按钮,它加载第二个带有两个文本框和一个提交按钮的表单。

首先,我需要一种传递文本框值给表单1(父)的方法,并使表单2关闭提交…

我该怎么做?直到现在,我已经写了这段代码,但它不工作

 private void button1_Click(object sender, EventArgs e)
        {
            emailForm EmailF = new emailForm();
            if ((EmailF.Username != null &&  EmailF.Password != null)) 
            {
                string user = EmailF.Username;
                string pass = EmailF.Password;
            }

和在emailForm.cs

 private void button1_Click(object sender, EventArgs e)
        {
            username = username_textbox.Text;
            password = username_textbox.Text;
            Close();
        }
        public string Username
        {
            get { return username; }
            set { this.username = value; }
        }
        public string Password
        {
            get { return password;}
            set { this.password = value; }
        }

从父窗体和子窗体传递参数值

你需要看看Form.ShowDialog()。这将做你想要的,当用户关闭对话框窗口时,你可以确保他们点击"确定"(或其他),然后从表单中获取值。

public void ShowMyDialogBox()
{
   Form2 testDialog = new Form2();
   // Show testDialog as a modal dialog and determine if DialogResult = OK.
   if (testDialog.ShowDialog(this) == DialogResult.OK)
   {
      // Read the contents of testDialog's TextBox.
      this.txtResult.Text = testDialog.TextBox1.Text;
   }
   else
   {
      this.txtResult.Text = "Cancelled";
   }
   testDialog.Dispose();
}