VB.NET应用模块获取TextBox默认值而非更新值的问题
VB.NET模块获取TextBox默认值而非用户更新值的解决方法
问题原因
模块Module1中直接通过窗体类名FrmLogin访问控件(如FrmLogin.TxtServerLocal.Text),这种方式会创建一个新的FrmLogin实例,而非用户正在操作的已加载窗体实例,因此获取到的是控件初始默认值,不是用户修改后的内容。
解决方案
方法一:传递当前窗体实例(推荐)
这种方式降低模块与窗体的耦合性,代码更易维护。
- 修改
Module1的connection方法,添加参数接收窗体实例:
Module Module1 Public con As MySqlConnection = New MySqlConnection() Public cs As String Public Sub connection(loginForm As FrmLogin) cs = "server=" & loginForm.TxtServerLocal.Text & ";database=" & loginForm.TxtDbLocal.Text & ";user=" & loginForm.TxtUserLocal.Text & ";password=" & loginForm.TxtPwdLocal.Text & ";port=" & loginForm.TxtPortLocal.Text & ";sslmode=required;" MsgBox("," & cs & "") con = New MySqlConnection(cs) End Sub End Module
- 在窗体的
BtnLogin_Click_1事件中调用方法时,传入当前窗体实例Me:
Call Module1.connection(Me)
方法二:通过静态实例访问(耦合性高,不推荐)
通过在窗体类中保存当前实例的静态引用,让模块直接访问该实例。
- 在
FrmLogin类中添加静态字段并初始化:
Public Class FrmLogin Public Shared CurrentInstance As FrmLogin Private Sub FrmLogin_Load(sender As Object, e As EventArgs) Handles MyBase.Load CurrentInstance = Me ' 原有Load事件代码... PanelLogin.Left = (Me.Width / 2) - 150 PanelLogin.Top = (Me.Height / 2) - 160 Dim filePath As String = (Application.StartupPath & "\cnd.dll") If File.Exists(filePath) Then Dim lines() As String = File.ReadAllLines(filePath) If lines.Length >= 1 Then TxtServerLocal.Text = lines(0) If lines.Length >= 2 Then TxtDbLocal.Text = lines(1) If lines.Length >= 3 Then TxtUserLocal.Text = lines(2) If lines.Length >= 4 Then TxtPwdLocal.Text = lines(3) If lines.Length >= 5 Then TxtPortLocal.Text = lines(4) End If End Sub ' 原有其他代码... End Class
- 修改
Module1的connection方法,使用静态实例:
Module Module1 Public con As MySqlConnection = New MySqlConnection() Public cs As String Public Sub connection() cs = "server=" & FrmLogin.CurrentInstance.TxtServerLocal.Text & ";database=" & FrmLogin.CurrentInstance.TxtDbLocal.Text & ";user=" & FrmLogin.CurrentInstance.TxtUserLocal.Text & ";password=" & FrmLogin.CurrentInstance.TxtPwdLocal.Text & ";port=" & FrmLogin.CurrentInstance.TxtPortLocal.Text & ";sslmode=required;" MsgBox("," & cs & "") con = New MySqlConnection(cs) End Sub End Module
注意事项
- 优先选择方法一,它遵循面向对象的设计原则,减少代码耦合。
- 禁止直接通过窗体类名访问控件,这会导致实例混淆,引发类似的取值错误。
内容的提问来源于stack exchange,提问作者shahzad khaliq
相关产品推荐
相关产品推荐

