对于所有人,我正在学习Visual Basic,我目前正在研究Windows应用程序。我有两个文本框方法(usernameTextBox
,passwordTextBox
)。用户将在其中输入数据,然后点击提交按钮(Button1_Click
)。该方法将调用connect。我希望能够做的是让用户键入他们的用户名和密码。然后在Button方法中调用它时,按值传递,而不是引用到connect()
。
有点像认证页面。现在我在connect(FirstName:="JohnDoe", Password:="password")
中有值 - 这基本上是用于测试MySQL服务器以及演示我想要尝试的内容。
Imports MySql.Data.MySqlClient
Public Class SecurePasswordList
Dim conn As New MySqlConnection
Public Sub connect(ByVal FirstName As String, ByVal Password As String)
Dim DatabaseName As String = "mysql"
Dim server As String = "10.1.0.0"
If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", server, FirstName, Password, DatabaseName)
Try
conn.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
connect(FirstName:="JohnDoe", Password:="password")
End Sub
Private Sub SecurePasswordList_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub usernameTextBox_TextChanged(sender As Object, e As EventArgs) Handles usernameTextBox.TextChanged
Dim FirstName As String
FirstName = usernameTextBox.Text
End Sub
Private Sub passwordTextBox_TextChanged(sender As Object, e As EventArgs) Handles passwordTextBox.TextChanged
Dim Password As String
Password = passwordTextBox.Text
End Sub
End Class
答案 0 :(得分:1)
更改
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
connect(FirstName:="JohnDoe", Password:="password")
End Sub
到
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
connect(FirstName, Password)
End Sub
但是你应该确保FirstName和Password被初始化并保存为类变量。 移动
Dim FirstName As String
Dim FirstName As String
在课堂上,而不是事件处理函数(点击等)。像这样:
Public Class SecurePasswordList
Dim conn As New MySqlConnection
Dim FirstName As String
Dim FirstName As String
但是你真的可以像这样重做你的代码(因为你想要的只是控件中的Text):
Imports MySql.Data.MySqlClient
Public Class SecurePasswordList
Dim conn As New MySqlConnection
Public Sub connect(ByVal FirstName As String, ByVal Password As String)
Dim DatabaseName As String = "mysql"
Dim server As String = "10.1.0.0"
If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", server, FirstName, Password, DatabaseName)
Try
conn.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
connect(usernameTextBox.Text, passwordTextBox.Text)
End Sub
End Class
我不认为通过价值或参考传递是这里的问题。你想连接函数修改传递给它的字符串吗?我对此表示怀疑。所以在这种情况下,价值或参考是好的。字符串由引用的复制实例传递,因此它们实际上是由Value传递的,除非在函数声明中使用Byref。默认情况下,每个类(int,string等)在VB中以不同方式传递。如果指定Byval或Byref,则需要检查每种类型以了解它将执行的操作。如果使用Byval,String会创建String的副本,但实际上是使用指向新创建的String的指针来访问它。所以这取决于你想要深入挖掘的深度