【问题标题】:accessing control in parent window from child window in c#从C#中的子窗口访问父窗口中的控件
【发布时间】:2010-11-11 23:03:45
【问题描述】:

我有一个主“父”窗口,其中包含一个按钮和一个文本框。 我有另一个窗口“子”窗口,当我在文本框中输入一些文本并单击主窗口上的按钮时会触发该窗口。现在子窗口包含另一个文本框和一个按钮。我需要做的是在子窗口的文本框中输入一些文本,然后当我点击子窗口上的按钮时,父窗口上的文本框应该使用我从子窗口输入的文本进行更新.. 这是示例:

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);
        }
    }
}

知道怎么做吗?

【问题讨论】:

标签: c# controls window parent


【解决方案1】:

1) 在 Form2 中(孩子一): 添加一个属性来获取TextBox中写入的文本:

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

并将按钮DialogResult 属性设置为Ok 以知道用户在关闭表单时按确定,而不是关闭按钮。

2) 在 Form1(父级)中: 检查用户是否按下了确定按钮,从 Form2 中的 theText 属性中获取值。

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

祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多