【问题标题】:How do I transfer information between forms? [duplicate]如何在表格之间传输信息? [复制]
【发布时间】:2019-08-02 08:25:06
【问题描述】:

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

但是它不起作用,表单 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;
       }

    }

【问题讨论】:

标签: c# winforms


【解决方案1】:

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

contactForm.ShowDialog();

txtFname.Text = contactForm.fname;

【讨论】:

    【解决方案2】:

    对您来说最简单的方法是使用contactForm.ShowDialog(),这样您就可以为一个 Button 分配 Dialog.OK 属性以使其关闭 contactForm 并返回到您的 Form A。为了使其更简单,请制作元素在您的contactForm Public 中输入类似txtFname.text = contactForm.txtUsername 的内容(当然这是在contactForm.ShowDialog() 之后)。

    【讨论】:

      【解决方案3】:

      像这样打开你的contactForm:

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

      否则你的 formContact 对话框对象在你触摸它的属性之前就被释放了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-06
        • 2020-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多