首页 > 解决方案 > 如何获取文本框值并将其设置为 VB 中的变量?

问题描述

我尝试连接到 postgressl 数据库。我有几个文本框可以询问用户详细信息,例如 IP 地址、数据库名称等...

当我尝试设置为可变文本框值时,会出现我的问题。错误信息是:System.NullReferenceException : Object reference not set to an instance of an object.

经过一些在线阅读后,我知道我遇到了这个错误,因为我尝试使用 null 的东西。我使用未初始化的引用(这是我第一次在 VB 中编码,所以我知道我错过了一些东西)。我不明白为什么我会收到这个错误。

调试器向我显示错误发生在这里:Dim user As String = TextBox1.Text。所以这意味着TextBox1.Text返回一些空值,不是吗?还是我使用错误的方法来获取文本框值?

Imports System.Windows
Imports System.Data.Odbc

Public Class UserControl1
    Dim myConnection As New System.Data.Odbc.OdbcConnection
    Dim user As String = TextBox1.Text, password As String = TextBox2.Text, ipServ As String = TextBox3.Text, dbName As String = TextBox4.Text
    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 = "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 & ";"


    Sub connexion_base_odbc(ByRef myConnection, ByVal cString, ByRef erreur)

        'Ouvre une connection vers une base de données ODBC

        '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 & ";"

        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
        Call connexion_base_odbc(myConnection, cString, erreur)
    End Sub
End Class

我想从中吸取教训,所以,如果可能的话,向我解释我在这里做错了什么,或者我的方法是否缺乏洞察力。

标签: vb.net

解决方案


嗯对不起,我认为这个问题与以正确的方式编写用户控件有关。


推荐阅读