vb.net - 如何获取文本框值并将其设置为 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 中正确注册用户控件 https://www.dotnetheaven.com/article/asp.net-usercontrol-by-vb.net
- 用户控件有多个同时运行的实例,因此可能在您的情况下使用正确的前缀调用其控件:this.textbox https://www.codeproject.com/Questions/194856/control-values-of-a-usercontrol-are-always -returni
- 初始化后应该使用控件,所以请阅读有关页面生命周期的文章并以正确的方式调用控件。
推荐阅读
- java - 如何在android中单击按钮显示可用的wifi网络?
- javascript - MomentJS 在满足特定条件时更改文本
- openvms - openvms 创建没有版本扩展名的文件(;1 等)
- c# - 在命名空间中找不到 System.Text.Json.JsonReaderException
- php - Laravel 5.8 并不总是更新新编写的代码
- spring-boot - 动态启动和关闭 KafkaListener 只是为了在会话开始时加载以前的消息
- python - 横幅仅适用于某些帐户
- c - C 文件未针对覆盖进行检测,错误的 expr 节点类型
- c++ - 在 C/C++ 中将 ASCII 转换为 unicode 字符串(无 API)
- firebase - Firebase 云数据库规则 - 如何仅在用户 id 与对象中的键匹配的地方检索数据?