这里还有一个初学者问题,来自 Delphi,你总是可以访问其他表单控件,但在我早期使用 C#/Visual Studio 时,我遇到了一个问题,事实证明这个问题比应有的更困难。
我开始编写一个简单的记事本样式应用程序,我有主窗体和用于选择行号的辅助窗体。
在我的主窗体中,我调用 goto 行号窗体,如下所示:
private void mnuGoTo_Click(object sender, EventArgs e)
{
Form gotoForm = new GoToForm();
var dialogResult = gotoForm.ShowDialog();
if (dialogResult == DialogResult.OK)
{
// get the text from gotoForm.editLineNumber.Text
MessageBox.Show(gotoForm.editLineNumber.Text); // doesn't work
}
}
正如您从注释代码中看到的,我有一个名为 editLineNumber
的 TextBox
控件,它位于我的另一个表单 (GoToForm
) 上。
我的问题(可能是初学者问题)是为什么当我输入 gotoForm.
时,editLineNumber
没有显示在 intellisense
菜单中?
如何从表单 GoToForm
访问 editLineNumber
控件?
//does not work
注释行的错误消息是:
Error CS1061 'Form' does not contain a definition for 'editLineNumber' and no extension method 'editLineNumber' accepting a first argument of type 'Form' could be found (are you missing a using directive or an assembly reference?)
除非我遗漏了一些明显的东西,否则为什么另一种表单上存在的控件不能公开供所有表单使用?我知道 C#/Visual Studio 与 Delphi 不同,但 Delphi 让您无需任何额外工作即可访问和查看所有表单上的所有控件的方式对我来说似乎更合乎逻辑。为什么 C#/Visual Studio 隐藏辅助窗体上的控件,这有什么好处?
最佳答案
editLineNumber
控件是私有(private)的。您可以将其更改为公开,但不鼓励这样做。
相反,请在 GoToForm
中创建一个返回所需值的属性。
public string LineNumber
{
get { return this.editLineNumber.Text; }
}
现在您可以引用您的新属性:
if (dialogResult == DialogResult.OK)
{
MessageBox.Show(gotoForm.LineNumber);
}
关于c# - 为什么我无法访问另一个表单上的文本框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38356333/