Why does the following code:
A = not IsDBNull(CurRow("BuyBook")) AndAlso CType(CurRow("BuyBook"), string) = "Yes"
results in the following error:
Conversion from type 'DBNull' to type 'String' is not valid.
When AndAlso is supposed to short-circuit according to this article:
http://support.microsoft.com/kb/817250
You are correct. AndAlso is short circuiting.
However, the error comes by calling CurRow("GuyBook") (verify this in a debugger to make sure I'm not a liar or making some crazy assumptions or just misremembering* ;-). Before you ask for a value, you need to ask the DataRow if it has a value. That is, use:
CurRow.IsNull("BuyBook")
Happy coding.
*One should just be able to compare with DBNull.Value or use IsDBNull. However, I am fairly certain that I ran into a row before that threw these exceptions instead of returning a DBNull object. Start by finding out -- in the Immediate Window of the Debugger -- exactly which expression throws the exception.
Have you tried comparing like this:
If CurRow("BuyBook") Is DBNull.Value Then
'...
End If
Instead of not IsDBNull(CurRow("BuyBook")), use NOT (CurRow("BuyBook")) is System.Dbnull.Value). Try this:
A = (NOT (CurRow("BuyBook")) is System.Dbnull.Value) AndAlso CType(CurRow("BuyBook"), string) = "Yes"
OR
A = not string.IsNullOrEmpty(CurRow("BuyBook")) AndAlso CType(CurRow("BuyBook"), string) = "Yes"
If dt.Rows(0)("BuyBook") = DBNull.Value Then
End If
Hope it helps.
In vb.net I usually do something like this:
A = (CurRow("BuyBook") & "" = "Yes")
Old trick from vb6 era. If CurRow("BuyBook") is null, vb.net will consider it as empty string when concatenating it with another string.
Related
How do I check for the existence of an item in a dropdownlist in vb.net?
Here's my not working code:
dim ddlTestDropdown as dropdownlist
ddlTestDropdown = New DropDownList()
If(ddlTestDropdown.Items.FindByValue("42") Is Not nothing)
Console.WriteLine("It's there")
End If
it won't let me compare the returned ListItem to nothing
Update: The error is from saying Is Not the fix is to say:
If(Not ddlTestDropdown.Items.FindByValue("42") Is Nothing)
Alternate answer:
Here's what I found to do this. Like #praythyus tried you need to test for contains, but vb.net only lets you do contains on a listitem. So I combined what I did with what he did and this worked:
Dim SetThisIfExists = ddlTestDropdown.Items.FindByValue("42")
If(ddlTestDropdown.Items.Contains(SetThisIfExists))
ddlTestDropdown.SelectedIndex = ddlTestDropdown.Items.IndexOf(SetThisIfExists)
End If
Sorry for giving C# syntax. Can you try with
as #RS said, you need to fill the ddl after initializing.
if(ddlTestDropdown.Items.Contains("42"))
{
}
Or instead of FindByValue can you use FindByText
Here is a record set.
...
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
...
adoCommand.CommandText = strQuery
Set adoRecordset = adoCommand.Execute
And I need to check this recordset has some value or not.
If adoRecordset.Fields("userid").Value Then
'do something...
Else
'do something...
End If
I just tried to check but this code makes occurs an error.
(The Error message below is translated by Google)
ADODB.Recordset Error '800a0cc1'
Item cannot be found in the collection corresponding to the requested name or ordinal
If possible, I want to use Ternary operator.
I don't know which part is wrong.
userid = adoRecordset.Fields("userid").Value ? adoRecordset.Fields("userid").Value : sw
Please understand that I'm a very newbie to asp, thank you.
You need to check for the existence of any rows in the resultset before attempting to access them by name:
If adoRecordset.eof Then
'//no rows
else
'//
There is no ternary operator in VBScript.
Try following example:
if adoRecordset.EOF Then
REM do something
else
REM do something
end if
I have a FormView where I pull data from one table (MS Access), and then insert it (plus more data) into another table. I'm having issues with the dates.
The first table has two date fields: date_submitted and date_updated. In some records, date_updated is blank. This causes me to get a data mismatch error when attempting to insert into the second table.
It might be because I'm databinding the date_updated field from the first table into a HiddenField on the FormView. It then takes the value from the HiddenField and attempts to insert it into the second table:
Dim hfDateRequestUpdated As HiddenField = FormView1.FindControl("hfDateRequestUpdated")
myDateRequestUpdated = hfDateRequestUpdated.Value
'... It then attempts to insert myDateRequestUpdated into the database.
It works when there is a value there, but apparently you can't insert nothing into a date/time field in Access. I suppose I could make a second insert statement that does not insert into date_updated (to use when there is no value indate_updated), but is that the only way to do it? Seems like there should be an easier/less redundant way.
EDIT:
Okay. So I've tried inserting SqlDateTime.Null, Nothing, and DBNull.Value. SqlDateTime.Null results in the value 1/1/1900 being inserted into the database. "Nothing" causes it to insert 1/1/2001. And if I try to use DBNull.Value, it tells me that it cannot be converted to a string, so maybe I didn't do something quite right there. At any rate, I was hoping that if there was nothing to insert that the field in Access would remain blank, but it seems that it has to fill it with something...
EDIT:
I got DBNull.Value to work, and it does insert a completely blank value. So this is my final working code:
Dim hfDateRequestUpdated As HiddenField = FormView1.FindControl("hfDateRequestUpdated")
Dim myDateRequestUpdated = Nothing
If hfDateRequestUpdated.Value = Nothing Then
myDateRequestUpdated = DBNull.Value
Else
myDateRequestUpdated = DateTime.Parse(hfDateRequestUpdated.Value)
End If
Thanks everyone!
Sara, have you tried casting the date/time before you update it? The data mismatch error likely comes from the fact that the hfDateRequestUpdated.Value you're trying to insert into the database doesn't match the column type.
Try stepping through your code and seeing what the type of that value is. If you find that it's a string (which it seems it might be, since it's coming from a field on a form), then you will need a check first to see if that field is the empty string (VBNullString). If so, you will want to change the value you're inserting into the database to DBNull, which you can get in VB.Net using DBNull.Value.
We can't see your code, so we don't know exactly how you get the value into the database, but it would look something like this
If theDateValueBeingInserted is Nothing Then
theDateValueBeingInserted = DBNull.Value
EndIf
Keep in mind that the above test only works if the value you get from the HiddenField is a string, which I believe it is according to the documentation. That's probably where all this trouble you're having is coming from. You're implicitly converting your date/time values to a string (which is easy), but implicitly converting them back isn't so easy, especially if the initial value was a DBNull
aside
I think what Marshall was trying to suggest was the equivalent of the above code, but in a shortcut expression called the 'ternary operator', which looks like this in VB.Net:
newValue = IF(oldValue is Nothing ? DBNull.Value : oldValue)
I wouldn't recommend it though, since it's confusing to new programmers, and the syntax changed in 2008 from IFF(condition ? trueResult : falseResult)
Your code
Dim myDateRequestUpdated As DateTime
myDateRequestUpdated = DateTime.Parse(hfDateRequestUpdated.Value) : DBNull.Value()
has a couple of problems:
When you declare myDateRequestUpdated to be DateTime, you can't put a DbNull.Value in it.
I'm not sure you need the () for DbNull.Value: it's a property, not a method (I don't know enough VB to say for sure)
VB doesn't know that : operator
What you probably want is a Nullable(Of DateTime) to store a DateTime value that can also be missing.
Then use something like this to store the value:
myDateRequestUpdated = If(String.IsNullOrWhiteSpace(hfDateRequestUpdated.Value),
Nothing, DateTime.Parse(hfDateRequestUpdated.Value))
If hfDateRequestUpdated.Value is empty, then use Nothing as the result; else parse the value as date (which might fail if it is not a valid date!).
Try this:
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim str As String
If TextBox1.Text.Length <> 0 Then
str = "'" & TextBox1.Text & "'"
Else
str = "NULL"
End If
sql = "insert into test(test1) values(" & str & ")"
dsave_sql(sql)
End Sub
Function save_sql(ByVal strsql As String, Optional ByVal msg As String = "Record Saved Sucessfully") As String
Dim sqlcon As New SqlConnection(strConn)
Dim comm As New SqlCommand(strsql, sqlcon)
Dim i As Integer
Try
sqlcon.Open()
i = CType(comm.ExecuteScalar(), Integer)
save_sql = msg
Catch ex As Exception
save_sql = ex.Message
End Try
sqlcon.Close()
Return i
End Function
We would like to compare a date from the db with current date.
Here is what I have tried so far:
'Obtain current date
Dim curdate As String = Now.ToString("yyyy")
'Now compare curdate with date from db called eventdate. Event date is of dateTime datatype.
If drv("eventdate").ToString = "" And Year(drv("eventdate").ToString) = curdate Then
'Then do some processing
End if
When I run this code, I get following error:
Conversion from string "" to type 'Date' is not valid.
Please help!
Thank you very much experts.
If Today.CompareTo(CDate(drv("eventdate")).Date) = 0 Then
'Do something
End If
I'm making the assumption here that you only care about the day, and not the time. Otherwise, the odds of having a match within a given day would be about 1 in 2.5 million.
Based on the comment:
If Today.Year.CompareTo(CDate(drv("eventdate")).Year) = 0 Then
'Do something
End If
or
If Today.Year = CDate(drv("eventdate")).Year Then
'Do something
End if
And one more thing: it really sounds like this is a check that should be done by your database. Make it part of the query that returns the results. This will be much faster, and it's where that kind of check belongs. All you'd need is add a check to your where clause like so:
Year(eventdate) = Year(current_timestamp)
If drv has an instance of DataReader then verify DBNull.
IF Not drv.IsDBNull(column_index_of_eventdate) Then
...
If drv.GetDateTime(column_index).Year=Date.Now.Year Then
...
End If
End If
I believe you have either a null or empty value, also your comparisn is wrong, try:
If drv("eventdate").ToString <> "" Andalso Year(drv("eventdate").ToString) = curdate Then
'Then do some processing
End if
When I write a code like below, I take this error message: "The query operator 'ElementAtOrDefault' is not supported."
How can I fix it?
Dim tmpQuestion As New UIData
Dim strViews = From t In tmpQuestion.LU_QUESTIONs _
Where t.ID_QUESTION = Request.QueryString("IdQuestion") _
Select t
Dim mtViews = strViews(0).MT_VIEWS
You haven't really queried yet.
strViews isn't the result set, it is the query. You need to actually retrieve some data.
var chosen = strViews.FirstOrDefault();
Have you tried using the FirstOrDefault() then check to make sure it is not null. My VB syntax is probably suspect, but you get the idea.
Dim strView = (From t In tmpQuestion.LU_QUESTIONS _
Where t.ID_QUESTION = Request.QueryString("IdQuestion") _
Select t).FirstOrDefault()
Dim mtViews as ...
If Not strView Is Nothing
mtViews = strView.MT_VIEWS
EndIf
I am no expert in VB or LINQ2SQL but does this not have anything to do with the fact that you say strViews(0).MT_VIEWS while there is a chance that strViews can be null?