有没有办法在 vb.net 中的表单之间传递值?(不使用公共变量)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18966080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to pass values between forms in vb.net? (Without using a public variable)
提问by Liewyec
I have an application that uses a second form with textBox and button, and i need to pass the text from textBox to the first form. I know how to do it with a public variable, but i would like to know if there is another way to do it without using a public variable.
我有一个应用程序,它使用带有 textBox 和按钮的第二个表单,我需要将文本从 textBox 传递到第一个表单。我知道如何使用公共变量来做到这一点,但我想知道是否有另一种方法可以在不使用公共变量的情况下做到这一点。
采纳答案by Steve
You can use PUBLIC properties on the second form to read/write info to the other form.
您可以使用第二个表单上的 PUBLIC 属性来读取/写入另一个表单的信息。
You can overload the NEW method to pass variable during declaration.
您可以重载 NEW 方法以在声明期间传递变量。
You can create a public sub/function on the second form and pass variable byval or byref.
您可以在第二种形式上创建一个公共子/函数并传递变量 byval 或 byref。
But, I would NEVER use a public variable. That is bad programming.
但是,我永远不会使用公共变量。那是糟糕的编程。
回答by char1es
Yes!
是的!
If the forms are part of the same solution, you simply write:
如果表单是同一解决方案的一部分,您只需编写:
Dim MyVal1 As Integer = Form2.MyVal
MyVal1 exists in whatever form you write it in, and MyVal2 comes from Form2. These variables can only be shared if the forms have the right privacy settings.
MyVal1 以您编写的任何形式存在,而 MyVal2 来自 Form2。只有当表单具有正确的隐私设置时才能共享这些变量。
If the two forms are part of separate applications, the only way i know of passing variables around is through constructors.
如果这两种形式是单独应用程序的一部分,我知道传递变量的唯一方法是通过构造函数。
EDIT:
编辑:
In your case with a textbox, you may be able to apply similar a solution:
在您使用文本框的情况下,您可以应用类似的解决方案:
Dim val As String = Form2.TextBox1.Text

