Friday, February 24, 2012

ADO.NET - I just dont get it!

Hi

I'm pulling my hair out with this one! I wrote the code below on a different computer, got it working fine, but when I copied it into another VB ASP.NET 2.0 web site - it doesn't work - no value is returned and I've checked the SQL is fine??? It doesn't through any errors, just doesn't work - can anyone see anything obvious?

ProtectedSub Page_Load(ByVal senderAsObject,ByVal eAs System.EventArgs)HandlesMe.Load

Dim connAsNew Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)

Dim SQLAsString =String.Format("SELECT photosLink FROM viewEvents WHERE eventID = 17")

Dim commAsNew Data.SqlClient.SqlCommand

Dim drAs Data.SqlClient.SqlDataReader

Dim photosLinkAsString =""Using conn

Try

conn.Open()

comm.Connection = conn

comm.CommandType = Data.CommandType.Text

comm.CommandText = SQL

dr = comm.ExecuteReader

DoWhile dr.Read

photosLink = dr("photosLink")

Loop

Catch exAs Exception

'err message is capture by assigning a variable to ex.Message

Finally

conn.Close()

EndTry

EndUsing

Label1.Text ="test " & photosLink

EndSub

Many thanks
Richard

Perhaps the database on the new web site doesn't have a photosLink WHERE eventID = 17

|||

Yea, it does, I've made absolutely sure. ??L

|||

The only other thing that looks suspect to me is the exception handler. As it is now, if there is an exception, it is masked and not reported.

Catch exAs Exception

'err message is capture by assigning a variable to ex.Message

Finally

|||

Good idea! (I'm fairly new to ASP.NET - as I'm sure you've guessed!).

The error comes up with 'Conversion from type 'DBNull' to type 'String' is not valid.'

How do I get round this one?

Thanks
Richard

|||

Hi,

From the error message you got, I think the cause of the problem is the following code:

photosLink = dr("photosLink")

What you got from dr("photosLink") is an Object typed value, and I guess currently the returned row according to your sql command is 0. So the return of dr("photoLink") has turned to be a System.DBNull typed object. And you are assigning the object to a string typed variable, which is not valid.

So please try to convert the object typed value to a string and then assign it to the local variable, See

photosLink = dr("photosLink").ToString()

Thanks.

|||

Thanks - that's fixed it! Thank you for taking the time to explain in detail, I've a big learning curve and appreciate your time.

Thanks again
Richard

No comments:

Post a Comment