Click to See Complete Forum and Search --> : Why can't this code run ?


Robert Chu
09-21-2006, 02:36 AM
Hello,
I met problems when I try to add items to a dropdownlist. The code is as below. But there is an error message: Object reference not set to an instance of an object. How can I fix it ? Thanks.

myConnection = New SqlConnection(ConfigurationSettings.AppSettings("connString"))
myConnection.Open()
myCommand = New SqlCommand(strSql,myConnection)
reader = myCommand.ExecuteReader()
Dim schemaTable As DataTable = reader.GetSchemaTable()
Dim dataRow As DataRow
For i =0 to schemaTable.Rows.Count -1
'dlMsgId.Items.add()
Response.Write(dataRow("MsgId"))
Next

John_Nick
10-17-2006, 08:37 AM
You have not declare the 'reader' variable
although you are using it as sqlreader.

So you just declare it and then use it...as following..

dim reader as sqldatareader

Cstick
10-17-2006, 10:29 PM
Assuming you did previously declare the sqldatareader, perhaps the problem is that you are trying to access the datarow before setting it?


myConnection = New SqlConnection(ConfigurationSettings.AppSettings("connString"))
myConnection.Open()
myCommand = New SqlCommand(strSql,myConnection)
reader = myCommand.ExecuteReader()
Dim schemaTable As DataTable = reader.GetSchemaTable()
For Each dataRow as DataRow In schemaTable.Rows
Response.Write(dataRow("MsgId"))
Next

Chitra Xavier
10-18-2006, 06:08 AM
Please check your Sql query string .Or, use my code for adding the values in dropdownlist.Its works fine.

Dim myConnection As SqlConnection = New SqlConnection("Server=INT14;uid=sa;pwd=sa;DataBase=Westlund")
myConnection.Open
Dim myCommand As SqlDataAdapter = New SqlDataAdapter("select Username from systemusers", myConnection)
Dim ds As DataSet = New DataSet
myCommand.Fill(ds)
Dim i As Integer = 0
While i < ds.Tables(0).Rows.Count
Me.DropDownList1.Items.Add(ds.Tables(0).Rows(i)("Username").ToString)
End While