I’m getting an error in this code that says: object reference not set to an instance of an object.
Private Sub frmAdd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = strcon
con.Open()
con.ConnectionString = strcon
How can I fix this error?
That means that you are using a variable that is null (it’s not set to point to an instance of any object). In this case,
conmust be null, so you need to check if it’s null, and if so, then set it to a new object. For instance:Or, better yet, just set it to a new object when you declare the variable, if that’s appropriate, for instance:
However, as Tim pointed out, it’s best to create a new connection each time you need one, and then you can use a
Usingblock which will properly dispose of the object every time: