accessing control in parent window from child window in c#

匆匆过客 提交于 2019-12-25 04:46:20

问题


I have a main "parent" window contains a button and a textbox. I have another window "child" window which fires when I enter some text in the textbox and click the button on the main window. now the child window contains another textbox and a button. what I need to do is to enter some text in the textbox on child window then when I hit the button on the child window the textbox on parent window should get updated with the text I entered from the child window.. here is the sample:

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace childform
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 tempDialog = new Form2(this);
            tempDialog.ShowDialog();
        }

        public void getText(string text)
        {
            textbox1.Text = text;
        }

    }
}

Form2.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace childform
{
    public partial class Form2 : Form
    {
        private Form1 m_parent;

        public Form2(Form1 frm1)
        {
            InitializeComponent();
            m_parent = frm1;
        }

        private void button1_Click(object sender, EventArgs e)
        { 
            m_parent.getText(textbox1.text);
        }
    }
}

any idea how to do this?


回答1:


1) In Form2 (The child one): Add a property to get the text which wrote in the TextBox:

Public string TheText
{
     get { return textbox1.Text; }
}

And set the button DialogResult property to Ok to know that the user press Ok when he closes the form, not the close button.

2) In Form1 (The parent): Check if the user pressed Ok button, add take the value from the property theText in Form2.

private void button1_Click(object sender, EventArgs e)
{
   Form2 tempDialog = new Form2();
   if (tempDialog.ShowDialog() == DialogResult.Ok)
      textbox1.Text = tempDialog.TheText;
}

Good luck!



来源:https://stackoverflow.com/questions/4160143/accessing-control-in-parent-window-from-child-window-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!