问题描述
我有一个主父窗口,其中包含一个按钮和一个文本框。
我还有另一个窗口子窗口,当我在文本框中输入一些文本并单击主窗口上的按钮时,该窗口将触发。现在,子窗口包含另一个文本框和一个按钮。我需要做的是在子窗口的文本框中输入一些文本,然后当我在子窗口上单击按钮时,父窗口的文本框应使用我从子窗口输入的文本进行更新。.
here是示例:
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
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);
}
}
}
任何想法?
推荐答案
1)在Form2中(子级):
添加属性以获取写入的文本TextBox:
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; }
}
并设置按钮 DialogResult
属性设置为 Ok
可以知道用户在关闭表单时按了Ok,而不是关闭按钮。
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)在Form1(父级)中:
检查用户是否按了确定按钮,然后从Form2中的theText属性中添加take值。
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;
}
祝你好运!
这篇关于在C#中从子窗口访问父窗口中的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!