tblMember :
membershipNo INT
firstName VARCHAR (50)
. .
. .
. .
样本表数据
membershipNo | firstName | .....
-------------+-----------+-----------
235 | Saman | ....
135 | John | ....
189 | Ruwan | ....
123 | Ada | ....
在另一个文本框中键入成员ID时,将编写以下代码以使用person的firstName填充文本框。但是在运行时键入成员ID时,会抛出以下错误消息
对象引用未设置为对象的实例
代码:
Private Sub txtMemID_TextChanged(sender As Object, e As EventArgs) Handles txtMemID.TextChanged
If con.State = ConnectionState.Open Then
con.Close()
End If
conn.Open()
Dim cmd As New SqlCommand("", conn)
Dim txtName As String
cmd.CommandText = "SELECT firstName FROM tblMember WHERE membershipNo = '" & txtMemID.Text & "'"
txtName = IIf(IsDBNull(cmd.ExecuteScalar), "", cmd.ExecuteScalar)
If txtName <> "" Then
txtMemberName.Text = txtName
Else
MsgBox("No Record Found!", MsgBoxStyle.Information, "INFO.")
End If
End Sub
例如:如果我开始输入189,则在txtMemID文本框中,当时txtMemName文本框应自动显示名称为Ruwan。如果我擦除ID也应该为空。然后再这样。