从另一个窗体访问一个窗体控件 [英] access a Form control from another Form

查看:120
本文介绍了从另一个窗体访问一个窗体控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在打开另一个表单.
Form1 Form2 有两种形式.

Form1 中,我有一个textBox1 Button1.
Button1将使用以下代码打开Form2

I am opening a form from another one.
Form1 and Form2 two forms are there.

In Form1 i am having a textBox1 and a Button1.
Button1 will open the Form2 using following Code

Form2 f2=new Form2();
f2.Show()


我没有关闭或隐藏Form1.
现在在form2 中,我还有另一个txtValue1 btn1.
我想在txtValue1 中输入一些文本,然后单击btn1.
form2 应该关闭,并且Form1textBox1 控件应包含txtValue1(Form2)的值.


请帮忙.我尝试了很多.但是我不能.


I am not closing or hiding the Form1.
now in form2 I am having another txtValue1 and btn1.
I want to enter some text in txtValue1 and then when I will click on btn1.
the form2 should get closed and the Form1''s textBox1 control should contain the value of txtValue1(Form2).


please help. I tried a lot. but I can''t.

推荐答案

Mika的答案是完全正确的,而且是一个很好的答案.
一种替代方法,也许就是您正在寻找的方法,是调用 ShowDialog [
Mika''s answer is perfectly valid and a good one at that.
An alternative, and perhaps what you are looking for, is calling ShowDialog[^] instead of simply Show. This means that the text in your Form2 has to be entered (or user cancels the form) before returning to Form1. This is usually an obvious choice because what purpose would Form2 still have if Form1 is closed?
Anyway, in that case you could put txtValue2 in a Property and read that from Form1, like so:
Form2 f2 = new Form2();
f2.ShowDialog(); // Execution of the code stops here until f2 is closed.
textBox1.Text = f2.MyTextProperty;
f2.Dispose();


希望能对您有所帮助:)


Hope that helps :)


这是有关表单协作的常见问题.最可靠的解决方案是在表单类中实现适当的接口.请查看我过去的解决方案以获取更多详细信息:如何以两种形式在列表框之间复制所有项目 [
This is the popular question about form collaboration. The most robust solution is implementation of an appropriate interface in form class. Please see my past solution for more detail: How to copy all the items between listboxes in two forms[^].

—SA




请尝试以下编码:

Form1:
Hi,

Try the below coding:

Form1:
private void button1_Click(object sender, EventArgs e)
{
 f2.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
  f2 = new Form2(this);
}



Form2:



Form2:

Form1 f;
public Form2(Form1 f1)
{
  InitializeComponent();
  f = f1;
}
private void button1_Click(object sender, EventArgs e)
{
  f.Activate();
  int value = Convert.ToInt32(textBox1.Text);
  f.textBox2.Text = value.ToString();
  this.Close();
}
}



问候,
vasuki.



Regards,
vasuki.


这篇关于从另一个窗体访问一个窗体控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆