从不同形式访问控件 [英] Accessing controls from different forms

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

问题描述

我有一个带有一些按钮,文本框,标签等的主表单。
在第二种表单上,我要将文本从主表单文本框中复制到第二种表单上。

I have a main form with some buttons, textboxes, labels, etc. On a second form I would like to copy the text from the main forms textbox onto the second form.

尝试过:

var form = new MainScreen();
TextBox tb= form.Controls["textboxMain"] as TextBox;
textboxSecond.Text = tb.Text;

但这只会导致异常。主屏幕文本框已初始化并包含文本。
当我将鼠标悬停在表单上时,我可以看到所有控件都在其中。

But it just causes an exception. The main screen textbox is initialised and contains text. When I hover over form I can see all the controls are there.

我在做什么

推荐答案

看看原始代码, NullReferenceException 您将得到。首先,您提供的代码中未定义 tb ,所以我不确定这是什么。

Looking at the original code, there are two potential reasons for the NullReferenceException you are getting. First, tb is not defined in the code you provide so I am not sure what that is.

其次, TextBox textbox = form.Controls [ textboxMain]作为TextBox 如果找不到控件,则可以返回 null > or 不是 TextBox 。控件默认情况下标有 private 访问器,这使我怀疑 form.Controls [...] 将为私人成员返回 null

Secondly, TextBox textbox = form.Controls["textboxMain"] as TextBox can return null if the control is not found or is not a TextBox. Controls, by default, are marked with the private accessor, which leads me to suspect that form.Controls[...] will return null for private members.

虽然将控件标记为内部可能会解决此问题,但这实际上不是解决此问题的最佳方法,只会在将来导致不良的编码习惯。控件上的 private 访问器非常好。

While marking the controls as internal will potentially fix this issue, it's really not the best way to tackle this situation and will only lead to poor coding habits in the future. private accessors on controls are perfectly fine.

在表单之间共享数据的更好方法是使用 public 个属性。例如,假设您在主屏幕上有一个 TextBox ,名为 usernameTextBox ,并希望将其公开公开给其他形式:

A better way to share the data between the forms would be with public properties. For example, let's say you have a TextBox on your main screen called usernameTextBox and want to expose it publicly to other forms:

public string Username
{
  get { return usernameTextBox.Text; }
  set { usernameTextBox.Text = value; }
}

那么您在代码中要做的就是:

Then all you would have to do in your code is:

var form = new MainForm();
myTextBox.Text = form.Username; // Get the username TextBox value
form.Username = myTextBox.Text; // Set the username TextBox value

此解决方案的重要之处在于,您可以更好地控制数据通过属性存储。您的 get set 操作可以包含逻辑,设置多个值,执行验证以及其他各种功能。

The great part about this solution is that you have better control of how data is stored via properties. Your get and set actions can contain logic, set multiple values, perform validation, and various other functionality.

如果您使用的是 WPF ,我建议您查找 MVVM 模式,因为它允许您对对象状态进行类似操作。

If you are using WPF I would recommend looking up the MVVM pattern as it allows you to do similar with object states.

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

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