You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET应用模块获取TextBox默认值而非更新值的问题

VB.NET模块获取TextBox默认值而非用户更新值的解决方法

问题原因

模块Module1中直接通过窗体类名FrmLogin访问控件(如FrmLogin.TxtServerLocal.Text),这种方式会创建一个新的FrmLogin实例,而非用户正在操作的已加载窗体实例,因此获取到的是控件初始默认值,不是用户修改后的内容。

解决方案

方法一:传递当前窗体实例(推荐)

这种方式降低模块与窗体的耦合性,代码更易维护。

  1. 修改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
  1. 在窗体的BtnLogin_Click_1事件中调用方法时,传入当前窗体实例Me:
Call Module1.connection(Me)

方法二:通过静态实例访问(耦合性高,不推荐)

通过在窗体类中保存当前实例的静态引用,让模块直接访问该实例。

  1. 在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
  1. 修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 22:09:56