How to pass textbox data between two forms?

后端 未结 3 586
旧巷少年郎
旧巷少年郎 2021-01-28 14:14

How to send textbox value to textbox between two forms without Show()/ShowDialog() by button? I want to textBox will get value without open form.

3条回答
  •  囚心锁ツ
    2021-01-28 14:44

    To pass information from a parent from to a child form you should create a property on the child form for the data it needs to receive and then have the parent form set that property (for example, on button click).

    To have a child form send data to a parent form the child form should create a property (it only needs to be a getter) with the data it wants to send to the parent form. It should then create an event (or use an existing Form event) which the parent can subscribe to.

    An example:

    namespace PassingDataExample
    {
        public partial class ParentForm : Form
        {
            public ParentForm()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                ChildForm child = new ChildForm();
                child.DataFromParent = "hello world";
    
                child.FormSubmitted += (sender2, arg) =>
                {
                    child.Close();
    
                    string dataFromChild = child.DataFromChild;
                };
    
                child.Show();
            }
        }
    }
    
    namespace PassingDataExample
    {
        public partial class ChildForm : Form
        {
            public ChildForm()
            {
                InitializeComponent();
            }
    
            public string DataFromParent { get; set; }
    
            public string DataFromChild { get; private set; }
    
            public event EventHandler FormSubmitted;
    
            private void button1_Click(object sender, EventArgs e)
            {
                DataFromChild = "Hi there!";
    
                if (FormSubmitted != null)
                    FormSubmitted(this, null);
            }
        }
    }
    

提交回复
热议问题