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

VB中获取TextBox值赋值变量遇System.NullReferenceException问题咨询

问题分析与解决方案

首先,你遇到的System.NullReferenceException错误根源非常明确:你在控件还没初始化的时候,就尝试访问它的属性了。

为什么会出错?

在VB.NET中,当你在类的级别(比如UserControl1的顶部)声明变量并直接赋值(比如Dim user As String = TextBox1.Text),这些变量的初始化会在控件的构造函数执行之前完成——而此时你的TextBox1、TextBox2等控件还没有被创建实例(也就是它们的值是Nothing,对应C#里的null)。这时候去访问TextBox1.Text,自然会抛出“对象引用未设置为对象的实例”的错误。

你的调试器已经指出错误在Dim user As String = TextBox1.Text这行,就是因为此时TextBox1还不存在,根本没法获取它的Text属性。

怎么修复?

你需要把获取TextBox值、拼接连接字符串的操作,移到控件已经初始化完成之后的时机——比如按钮的点击事件里,或者UserControl_Load事件里。因为只有当控件加载完成后,这些TextBox才真正被创建,你才能安全访问它们的属性。

修改后的代码示例:

Imports System.Windows
Imports System.Data.Odbc
Public Class UserControl1
    ' 只声明变量,不在类级别提前赋值
    Dim user As String, password As String, ipServ As String, dbName As String
    Dim selectRequest As String, crudRequest As String
    Dim erreur As Boolean
    ' 这些固定配置可以保留在类级别
    Dim driver As String = "{PostgreSQL Unicode}", port As Integer = 5432, pooling As String = "True", minPoolSize As Integer = 0, maxPoolSize As Integer = 100, coLifetime As Integer = 0
    Dim cString As String

    Sub connexion_base_odbc(ByRef myConnection, ByVal cString, ByRef erreur)
        Try
            myConnection.ConnectionString = cString
            myConnection.Open()
            MessageBox.Show("Connexion réussie !")
        Catch ex As Exception
            MessageBox.Show("Problème lors de la connection à la base. " & ex.Message)
            erreur = True
            Exit Sub
        End Try
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ' 在这里获取TextBox的值!此时控件已经完全初始化
        user = TextBox1.Text
        password = TextBox2.Text
        ipServ = TextBox3.Text
        dbName = TextBox4.Text

        ' 现在才拼接连接字符串,用的是用户刚输入的内容
        cString = "Driver=" & driver & ";Uid=" & user & ";Pwd=" & password & ";Server=" & ipServ & ";Port=" & port & ";Database=" & dbName & ";Pooling=" & pooling & ";Min Pool Size=" & minPoolSize & ";Max Pool Size=" & maxPoolSize & ";Connection Lifetime=" & coLifetime & ";"

        connexion_base_odbc(New OdbcConnection(), cString, erreur)
    End Sub
End Class

额外的优化建议

  1. 添加输入校验:在尝试连接之前,检查用户是否填写了必要的字段(比如IP、数据库名、用户名),避免因为空值导致连接失败:
    If String.IsNullOrEmpty(ipServ) OrElse String.IsNullOrEmpty(dbName) OrElse String.IsNullOrEmpty(user) Then
        MessageBox.Show("Veuillez remplir tous les champs obligatoires !")
        Return
    End If
    
  2. 使用Using语句管理数据库连接:数据库连接是稀缺资源,用Using可以自动在代码块结束后关闭并释放连接,避免资源泄漏:
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        user = TextBox1.Text
        password = TextBox2.Text
        ipServ = TextBox3.Text
        dbName = TextBox4.Text
    
        ' 输入校验
        If String.IsNullOrEmpty(ipServ) OrElse String.IsNullOrEmpty(dbName) OrElse String.IsNullOrEmpty(user) Then
            MessageBox.Show("Veuillez remplir tous les champs obligatoires !")
            Return
        End If
    
        cString = "Driver=" & driver & ";Uid=" & user & ";Pwd=" & password & ";Server=" & ipServ & ";Port=" & port & ";Database=" & dbName & ";Pooling=" & pooling & ";Min Pool Size=" & minPoolSize & ";Max Pool Size=" & maxPoolSize & ";Connection Lifetime=" & coLifetime & ";"
    
        erreur = False
        ' Using自动管理连接的生命周期
        Using conn As New OdbcConnection(cString)
            Try
                conn.Open()
                MessageBox.Show("Connexion réussie !")
            Catch ex As Exception
                MessageBox.Show("Problème lors de la connection à la base. " & ex.Message)
                erreur = True
            End Try
        End Using
    End Sub
    
  3. 避免Call关键字:在VB.NET中,Call关键字已经是过时的写法,直接调用方法即可,代码会更简洁。

内容的提问来源于stack exchange,提问作者LyessD

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:23:20