如何在表格之间传输信息?

时间:2019-07-26 13:48:02

标签: c# winforms

我正在尝试将信息从表单B传输到表单A。基本上,表单A有一个打开新表单(表单B)的按钮,然后表单B有一个供您输入文本的文本框。然后,当您关闭窗体B(通过关闭按钮)时,应该使用窗体B中输入的文本来更新窗体A中的文本框。

无论如何,表单A的文本框都无法接收在表单B中输入的文本,这给了我一个空值。

//main class of Form A (the one that has to recieve into from Form B)
public partial class FormManager : Form
    {
        //creating an instance of Form B
        FormContact contactForm;
        public string a;

        public FormManager()
        {
            InitializeComponent();
            ControlsDisabled();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            //trying to fill in a textbox from form B into form A
            contactForm = new FormContact();
            contactForm.Show();
            this.Refresh();
            txtFname.Text = contactForm.fname;
            //^^^the main problem, this value is null
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            contactForm = new FormContact(txtFname.Text, txtLname.Text);
            contactForm.Show();
        }

//main class of form B(the form that has to give info to form A)
 public partial class FormContact : Form
    {
       public string fname;
       public string lname;

       public FormContact()
       {
           InitializeComponent();
       }

       private void btnSave_Click(object sender, EventArgs e)
       {
          fname = txtFnameA.Text;
          lname = txtLname.Text;
          this.Refresh();
          this.Close();
       }
       public FormContact(string Fname, string Lname)
       {
           InitializeComponent();
           txtFnameA.Text = Fname;
           txtLname.Text = Lname;
       }

    }

3 个答案:

答案 0 :(得分:0)

在用户有机会输入值之前,显示fname后立即读取FormContact值。请尝试以下操作:

contactForm.ShowDialog();

txtFname.Text = contactForm.fname;

答案 1 :(得分:0)

最简单的方法是使用contactForm.ShowDialog(),为此您可以为一个Button分配Dialog.OK属性,以使其关闭contactForm并返回到窗体A。 contactForm Public中的元素,因此您可以输入类似txtFname.text = contactForm.txtUsername的内容(当然,这是在contactForm.ShowDialog()之后输入的。)

答案 2 :(得分:0)

像这样打开您的contactForm:

using (var contactForm = new FormContact())
{
    if (contactForm.ShowDialog() == DialogResult.OK)
    {                    
        txtFname.Text = contactForm.fname;              
    }    
}

否则,将释放formContact对话框对象,然后才能触摸其属性。