在Form1的方法中使用Form 2上的组件 [英] Use components on Form 2 in methods of Form1

查看:104
本文介绍了在Form1的方法中使用Form 2上的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Windows窗体应用程序中创建了2个窗体.

我在Form2上放置了文本框和组合框.我想在Form1的方法中调用组合框和文本框.基本上,我想在Form 1的方法中使用Form 2上的组件.

如何在Form 1的方法中调用Form 2上的组件?

I have created 2 Forms in a Windows Form Application.

I have putted textboxes and comboboxes on Form2. I want to call the Comboboxes and Textboxes in the methods of Form1. Basically, I want to use the components that are on Form 2 in the methods of Form 1.

How can I call components that are on Form 2 in the methods of Form 1? Is it possible?

推荐答案

"Don''t"是简单的答案.

您可以,但是强烈建议您不要这样做.

如果要访问Form2上控件的内容,请使用公共属性间接获取和设置它们.这样一来,Form2的设计就不会一直固定在石头上.

如果要在两种不同的表单上使用同一组控件,则将它们创建为UserControl(具有适当的公共属性),并在每种表单上使用其实例.
"Don''t" is the simple answer.

You can, but it is very, very strongly advised that you don''t.

If you want to access the contents of controls on Form2, then use public properties to get and set them indirectly. That way the desig of Form2 is not locked in stone for all time.

If you want to use the same group of controls on two different forms, then create them as a UserControl (with appropriate public properties) and use an instance of that on each form.


这是关于表单协作的热门问题.最健壮的解决方案是在Form类中实现适当的接口,并传递接口引用而不是对Form的整个实例"的引用.请查看我过去的解决方案以获取更多详细信息:如何以两种形式在列表框之间复制所有项目 [
This is the popular question about form collaboration. The most robust solution is implementation of an appropriate interface in form class and passing the interface reference instead of reference to a "whole instance" of a Form. Please see my past solution for more detail: How to copy all the items between listboxes in two forms[^].

—SA


是的,有可能
参见示例

yes it is possible
See the example

Form2 f = new Form2();
           f.Show();
           Control[] c= f.Controls.Find("comboBox1", false);
           ComboBox cb = (ComboBox)c[0];
           cb.Width = 500;


这篇关于在Form1的方法中使用Form 2上的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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