使用C#Windows应用程序将一种表单控制用于另一种表单 [英] one form contol used to another form using c# windows application

查看:110
本文介绍了使用C#Windows应用程序将一种表单控制用于另一种表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个Windows应用程序,它使用两种形式,例如form1和form2.

第一种形式只设计了两个文本框.另一种形式设计了一个按钮.

现在第二个表单如何访问文本框的第一个表单控件.


即button_click()

one windows application using 2 forms like form1 and form2.

first form designed two textbox only. another one form designed one button.

now the second form how to access first form controls of textbox.


that is, button_click()

{
string a=textbox1.text;
string b=textbox2.text;
console.writeline(a);
console.writeline(b);
}

推荐答案

首先,您必须为第一种形式创建或创建变量
例如:
First u have to make or create a variable for the first form
ex:
form1 obj=new form1();


现在


now

str=obj.textbox1.text;


这样,我们可以尝试使用


like this we can use just try


简单答案:不要.

当您这样做时,将两个表单的设计联系在一起.如果不考虑对另一种表单的影响,就无法更改一种表单的工作方式.这违反了OOP的原理,并且对可靠性有不利影响.

而是设置公共属性和/或事件来传输数据.这样,表单的内部工作就不会暴露给外界.

最好的方法是以适当的形式创建一个事件,该事件指示有新数据可用,并以另一种形式订阅该事件.这样,如果第二种形式对数据感兴趣,则可以使用它,或者如果第二种形式不使用该数据,则不处理该事件.
Simple answer: Don''t.

When you do that, you tie the design of the two forms together. You cannot make a change to the way one form works, without considering the effects on the other. This is against the principles of OOP, and has a detrimental effect on reliability.

Instead, set up public properties and / or events to transfer the data instead. That way the internal working of the form do not get exposed to the outside world.

The best way to do it is to create an event in the appropriate form which indicates that new data is available, and subscribe to that event in the other form. That way, if the second form is interested in teh data, it can use it, or not handle the event if it is not going to use the data.


使控件公开.
并在Form2.cs中用作
Make control public.
and use in Form2.cs as
Form1 f1=new Form1();
string s1=f1.TextBox1.Text;



如果您不想公开控件,请使用属性.


or
use properties if you do''nt want to make control public.


这篇关于使用C#Windows应用程序将一种表单控制用于另一种表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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