Cast from type 'DBNull" to type 'String' is not valid

Please support our ASP.NET advertiser: Intel Parallel Studio Home
Reply

Join Date: Mar 2007
Posts: 34
Reputation: shy_wani is an unknown quantity at this point 
Solved Threads: 0
shy_wani shy_wani is offline Offline
Light Poster

Cast from type 'DBNull" to type 'String' is not valid

 
0
  #1
Apr 4th, 2007
hi..
my system should select the maximum QuestionNum from one of the my table in the database. after all, i would like to increment the value QuestionNum to 1...
but i keep on receiving error
"Cast from type 'DBNull' to type 'String' is not valid."

this is my code...

Public Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
Dim MyConnection As SqlConnection
MyConnection = New SqlConnection("server=localhost;database=xxxxxxx;Trusted_Connection=yes")
MyConnection.Open()
Dim sql As String
//Select the max QuestionNum where SurveyID=SurveyID
sql = "SELECT MAX(QuestionNum) FROM Question WHERE SurveyID='" & Session("sSurveyID") & "'"
Dim cmd As New SqlCommand(sql, MyConnection)
Dim QuestionNum As Integer
Dim id As String
id = cmd.ExecuteScalar
QuestionNum = id
MyConnection.Close()
End If
End Sub


p/s: can anyone explain what is wrong here?
Reply With Quote Quick reply to this message  
Join Date: Mar 2007
Posts: 2
Reputation: nitinmms is an unknown quantity at this point 
Solved Threads: 0
nitinmms nitinmms is offline Offline
Newbie Poster

Re: Cast from type 'DBNull" to type 'String' is not valid

 
0
  #2
Apr 4th, 2007
Hi,

What's hapenning is that the SurveyID which you are passing in Session variable does not have any Questions as yet in the table and so Null is returned.

Please change Max(QuestionNum) to Isnull(Max(QuestionNum),0)

as below:

  1. //Select the max QuestionNum where SurveyID=SurveyID
  2. sql = "SELECT isnull(MAX(QuestionNum),0) FROM Question WHERE SurveyID='" & Session("sSurveyID") & "'"

Regards,

Nitin
Reply With Quote Quick reply to this message  
Join Date: Mar 2007
Posts: 34
Reputation: shy_wani is an unknown quantity at this point 
Solved Threads: 0
shy_wani shy_wani is offline Offline
Light Poster

Re: Cast from type 'DBNull" to type 'String' is not valid

 
0
  #3
Apr 5th, 2007
owh..thanks nitinmms

now i understand...this problem has been bugging me since last week..haha..

thanks again yer...
take care
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC