[英]How to modify controls from a different form in C#
Is there a way to modify the text in a textbox, or something like that from a different form? 有没有一种方法可以修改文本框中的文本,或者通过其他形式修改文本?
In my program, I need to spawn a new Form2, and have all the textboxes hold information based on stuff entered in Form3. 在我的程序中,我需要生成一个新的Form2,并让所有文本框都根据在Form3中输入的内容保存信息。 So far I've only done: 到目前为止,我只做过:
Form2 form2 = new Form2();
form2.Show();
I just don't know how to access form2.textbox1.Text, for example, from form3. 我只是不知道如何例如从form3访问form2.textbox1.Text。 I've looked online but didn't find quite what I was looking for, and I've tried a few different things with no success. 我在网上看了一下,但没有找到想要的东西,并且尝试了几种不同的尝试,但都没有成功。
Thanks! 谢谢! :) :)
Pass the instance of Form2
into Form3
: 将Form2
的实例传递到Form3
:
public Form3(Form2 referrer)
{
var txt = referrer.TextBox1Text;
}
and then when calling it: 然后在调用它时:
Form3 f3 = new Form3(this);
f3.Show();
and you'll just have to make sure that you build a property on Form2
like this: 并且只需要确保您像这样在Form2
上构建属性:
internal string TextBox1Text { get { return textBox1.Text; } }
The problem is that the controls defined in each form are not public objects, so you can't access them from outside the form. 问题在于,每个表单中定义的控件都不是公共对象,因此您不能从表单外部访问它们。
Why don't you define a public method in each form to retrieve/set the value you need from the controls you need? 为什么不在每种形式中定义一个公共方法来从所需的控件中检索/设置所需的值?
I think that it would be a better approach than exposing your controls. 我认为这是比公开控件更好的方法。
Assuming that you are instantiating the Form2 within the code behind of Form3 (calling "new" Form2())... 假设您要在Form3后面的代码中实例化Form2(调用“新” Form2())...
You can create a public method within Form2 that will provide the accessibility you need. 您可以在Form2中创建一个公共方法,该方法将提供所需的可访问性。 Example: 例:
(within Form2 - code behind) (在Form2中-后面的代码)
public SetTextboxTextProperty(string text)
{
this.Textbox1.Text = text;
}
From Form3: 从Form3:
Form2 form2 = new Form2();
form2.SetTextboxTextProperty("your data");
form2.Show();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.