如何删除此错误,即“对象引用未设置为对象的实例”? [英] How can I remove this error, i.e "Object reference is not set to an instance of an object"?
本文介绍了如何删除此错误,即“对象引用未设置为对象的实例”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Imports System.Data.SqlClient
Public Class frmCustomerEdit
Dim con As SqlConnection
Private Sub frmCustomerEdit_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'TestdbDataSet.Customersdb' table. You can move, or remove it, as needed.
Me.CustomersdbTableAdapter.Fill(Me.TestdbDataSet.Customersdb)
'TODO: This line of code loads data into the 'TestdbDataSet.Customersdb' table. You can move, or remove it, as needed.
Me.CustomersdbTableAdapter.Fill(Me.TestdbDataSet.Customersdb)
Try
con.ConnectionString = "Data Source=SuperComp-PC;Initial Catalog=Testdb;Integrated Security=True"
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim sDate As Date = Me.DateTimePicker1.Value
Dim eDate As Date = Me.DateTimePicker2.Value
Dim abc As String = " Update Customersdb set CName='" & TextBox2.Text & "', Address='" & RichTextBox1.Text & "', Delivery_Charge='" & TextBox3.Text & "', Start_Date='" & sDate & "', End_Date='" & eDate & "' Where Customer_ID='" & TextBox1.Text & "';"
Dim da As New SqlDataAdapter(abc, con)
Dim ds As New DataSet
da.Fill(ds)
MsgBox("UPDATE SUCESSFUL !")
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Me.Close()
frmCustomer.Show()
End Sub
End Class
推荐答案
好吧,两件事:
1)将解决眼前的问题。你声明con
,但你永远不会给它一个值!在某些时候,您需要将con设置为SqlConnection的实例,因此请将其替换为:
Well, two things:
1) Will fix the immediate problem. You declarecon
, but you never give it a value! At some point you need to set con to an instance of an SqlConnection, so replace this:
con.ConnectionString = "Data Source=SuperComp-PC;Initial Catalog=Testdb;Integrated Security=True"
这样:
With this:
con = New SqlConnection("Data Source=SuperComp-PC;Initial Catalog=Testdb;Integrated Security=True")
2)不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。请改用参数化查询。
2) Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
这篇关于如何删除此错误,即“对象引用未设置为对象的实例”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文