Friday, March 16, 2012

Object reference not set to an instance of an object.

Hi I just started learning ASP.NET not too long ago and I have this problem here with me that I cannot solve. I hope I am able to get some help here.

Here's my problem: I get a message saying "Object reference not set to an instance of an object."

Below are my codes.


Dim objConn As OleDbConnection
objConn = New OleDbConnection
Dim objCommand As OleDbCommand
objCommand = New OleDbCommand
Dim objAdapter As OleDbDataAdapter
objAdapter = New OleDbDataAdapter
Dim objDataSet As DataSet
objDataSet = New DataSet
Dim strConnectionString As String
Dim strSQLCommand As String

strConnectionString = "Provider=SQLOLEDB.1; Data Source=localhost; Initial Catalog=Project 1;"
strSQLCommand = "SELECT * FROM tblShopList"
objConn.ConnectionString = strConnectionString
objCommand.Connection = objConn
objCommand.CommandText = strSQLCommand
objAdapter.SelectCommand.Connection.Open()

objAdapter.Fill(objDataSet, "tblShopList")

grdShopList.DataSource = objDataSet.Tables("tblShopList")
grdShopList.DataBind()

objAdapter.SelectCommand.Connection.Close()

I am using IIS as my web server and MSSQL for my database. I suppose my error is in my connectionstring. Anybody can help? Thanks so much!which line throws it?

I could probably guess, but I don't wish to.
I've rewritten the code to a smooth code snippet that takes care of it all. If you have questions, please come to me via the forums:

Imports System.Data
Imports System.Data.SqlClient

Dim dsn As String = "server=localhost;uid=user;pwd=pass;database=Project 1" 'change the user name and password accordingly
Dim conn As New SqlConnection(dsn) 'use a System.Data.SqlClient.SqlConnection instead of OleDb to have better performane while working with SQL Server
Dim ds As New DataSet()

Try
Dim query As String = "SELECT * FROM tblShopList"
Dim cmd As New SqlCommand(query, conn)
Dim adapter As New SqlDataAdapter(cmd)

conn.Open()
adapter.Fill(ds, "tblShopList")
Catch ex As Exception
'take actions if something fails
Finally
conn.Close() 'will always close the connection, even when an error occurred
End Try

grdShopList.DataSource = ds.Tables(0)
grdShopList.DataBind


Hi I just want to say thanks so much for your help here! You are really great!
Hi, sorry but I needed to ask you this. For the user name and password in the dsn string, what should I put? My SQL Server is using windows authentication and not SQL authentication. Thanks a lot!!
hi.. thanks I've already sorted out most of the codes but I've encountered another error which goes like this:

Login failed for user 'cloud'

the code that's throwing the error is like this


objAdapter.SelectCommand.Connection.Open()

for the whole code it's the one above. thanks again!!

0 comments:

Post a Comment