如何获取文本框值并将其设置为VB中的变量?

时间:2019-05-09 13:12:46

标签: vb.net visual-studio odbc

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

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

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

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

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

我想从中学到东西,所以,如有可能,请向我解释我在这里做错了什么,或者我的方法缺乏见识。

1 个答案:

答案 0 :(得分:-2)

嗯,抱歉,我认为此问题与以正确方式编写用户控件有关。