Why is this program not entering my ElseIf statement -- System.DBNull - asp.net

I imported an Excel file into an ASP.NET DataTable. Some of the values are blank, specifically at indexes 2 and 3, and I would like to set those blank fields to 0.
When debugging, the values for row.item(2) and row.item(3) are both System.DBNull. Interestingly enough, the program enters the If statement and sets row.item(2) value to 0, but it never enters the ElseIf statement. What is going on? Here's my code:
If row.Item(2) Is Nothing OrElse row.Item(2).ToString = "" OrElse IsDBNull(row.Item(2)) Then
dt.Rows.Item(i).SetField(2, 0)
ElseIf row.Item(3) Is Nothing OrElse row.Item(3).ToString = "" OrElse IsDBNull(row.Item(3)) Then
dt.Rows.Item(i).SetField(3, 0)
End If
EDIT:
Per Tim's suggestion, I revised my code as follows:
If Not row.Field(Of Int32?)(2).HasValue Then
dt.Rows.Item(i).SetField(2, 0)
End If
If Not row.Field(Of Int32?)(3).HasValue Then
dt.Rows.Item(i).SetField(3, 0)
End If
However, this is throwing an error--Object cannot be cast from DBNull to other types
When debugging, in the first loop:
row.Item(2) = 17
row.Item(3) = 1
Theoretically, it should skip this iteration and proceed to the next. However, my program immediately catches the exception with the above error.

Since your if is executing, your else if will not execute.
If you want your else if logic to execute even if your if executes, just make it it's own if block:
If row.Item(2) Is Nothing OrElse row.Item(2).ToString = "" OrElse IsDBNull(row.Item(2)) Then
dt.Rows.Item(i).SetField(2, 0)
End If
If row.Item(3) Is Nothing OrElse row.Item(3).ToString = "" OrElse IsDBNull(row.Item(3)) Then
dt.Rows.Item(i).SetField(3, 0)
End If

You don't provide sample data so we just have to guess. But my guess is that you want two If statements.. not an ElseIf. ElseIf will only evaluate if the If statement returns false.

Related

Comparing object with Nothing in vb.net

I have a code
Dim drQues As DataRow = dtQuestion.AsEnumerable()
.First(Function(uqno) uqno.Field(Of Int32)("uniqueqno") = drqno("uniqueqno"))
I want to check if drQues is Nothing
I tried
If Not drQues <> Nothing THEN
but it says
<> is not defined for System.Data.DataRow and System.Data.DataRow
how can I check if there was a row for specified condition in linq?
Use Is or IsNot where the usual comparison operators are not defined.
If drQues Is Nothing Then

Error when accessing cookies when a cookies without a name exists

On a few of the Classic ASP websites I manage for the last few days I have been getting some error notifications (with no error number) that always show an error on a line number where a cookie value is being requested.
Looking at the request for each of these errors, they all have unusual cookies, and look like some sort of hack attempt.
The lines that are indicated as causing the error are all like this:
strCookieCart = Request.Cookies("cart")
Here's a couple of samples of the cookies being sent (truncated)... Note the =true (no name, just a value).
HTTP_COOKIE:=true; yuv=u97Yoe-o0UWp7ho_vaB2csT-xxaQ37gMWzhB1MARTSNk1QKpjJTXmZYMRQ095rM96MaNbhx1tEdJ
HTTP_COOKIE:pll_language=en; =true; yandexuid=6536735381437958890; st=6c9838994ffb
Is Classic ASP incapable of handling these? Is there any way to avoid these errors and ignore the bad values? Are these always likely to be hack attempts or could there be legitimate requests without cookie names?
I suppose I could check for these looking at Request.ServerVariables("HTTP_COOKIE") by manually parsing or using a regular expression check of some sort. Does anyone else do this? Any code to share?
A second answer to my own question and the solution I have now implemented is to add the following code to my common include file.
It tests whether Classic ASP can read the cookies and, using error trapping, ends the response if an error is detected.
On Error Resume Next
Request.Cookies("test")
If Err.Number <> 0 Then Response.End
On Error Goto 0
This is a better solution to my other answer as there is no point in generating a page for what is obviously an attack of some sort so ending the script as soon as possible is a better choice.
My proposed answer to my own question is to create a class that extracts all the valid keys and values for the cookies on initialisation, and has a function to return a value for a specified key.
Unfortunately it doesn't work for cookies that contain a collection of multiple values, but I don't generally use these anyway.
Here is the class:
<%
Class MyRequest
Private m_objCookies
Private Sub Class_Initialize()
Dim strCookies, i, strChar, strName, strValue, blnInValue
strCookies = Request.ServerVariables("HTTP_COOKIE")
Set m_objCookies = Server.CreateObject("Scripting.Dictionary")
i = 1
strName = ""
strValue = ""
blnInValue = False
Do
strChar = Mid(strCookies, i, 1)
If strChar = ";" Or i = Len(strCookies) Then
strValue = Trim(strValue)
If strName <> "" And strValue <> "" Then
If m_objCookies.Exists(strName) Then
m_objCookies.Item(strName) = strValue
Else
m_objCookies.Add strName, strValue
End If
End If
If i = Len(strCookies) Then Exit Do
strName = ""
strValue = ""
blnInValue = False
ElseIf strChar = "=" Then
strName = Trim(strName)
blnInValue = True
ElseIf blnInValue Then
strValue = strValue & strChar
Else
strName = strName & strChar
End If
i = i + 1
Loop
End Sub
Public Function Cookies(strKey)
Cookies = m_objCookies.Item(strKey)
End Function
End Class
%>
The changes to my code to use this class are minimal. Where I currently have...
strCookieCart = Request.Cookies("cart")
I will need to change to...
Dim objMyRequest : Set objMyRequest = New MyRequest
strCookieCart = objMyRequest.Cookies("cart")
I have tested the above with many of the bad requests I have logged and it works fine.
Add three line codes for #johna is answer, after this line:
If strChar = ";" Or i = Len(strCookies) Then
add these lines:
If i = Len(strCookies) And strChar <> ";" Then
strValue = strValue & strChar
End If

Why is my if statement not firing

I did a simple experiment to make sure I know what is going on as I'm new to programming. This has me stumped and I'm getting angry with my computer for lying to me. :)
Here is my vb.net
If table2.Rows.Count = 0 Then
LBLCannary.Visible = True
End If
Now if I hover over during debug it tells me the count is zero. ie table2.Rows.Count 0 but for some odd reason it never goes to the next line in the if. if the table is empty. Why won't it work?
Answer: Silly newbie mistake, All this is done after return and nothing happens after a function returns something.
Can you try the reverse?
If table2 IsNot Nothing AndAlso table2.Rows.Count > 0 Then
'do nothing
Else
'if no rows or if table is empty
LBLCannary.Visible = True
End If
or widen your condition to
If table2 Is Nothing OrElse table2.Rows.Count < 1 Then
LBLCannary.Visible = True
End If

Using or in a conditional statement

I have a conditional statement in Page_Load that checks if the value of a text box is blank. however, I also want to test for null as well. I'm having some issue with my syntax.
This is my conditional statement (works well):
If (textUserName.Text.ToString <> "") Then
textUserName.[ReadOnly] = True
End If
My question is, how can I check for null as well using "or" (preferred)?
...perhaps using elseif
This is what I've tried using "elseif":
If (textUserName.Text.ToString <> "") Then
textUserName.[ReadOnly] = True
ElseIf (textUserName.Text.ToString <> vbNull) Then
textUserName.[ReadOnly] = True
End If
Though my application functions well w/ the condition I'm using, plus the field for the username is set in the database to not allow Nulls, I was just curious as to how I would set my condition if I had to deal with a Null value. Thanks
Use String.IsNullOrEmpty to check for null strings
If textUserName.Text <> "" Or Not String.IsNullOrEmpty(textUserName.Text) Then
textUserName.[ReadOnly] = True
End If
Or... Which I believe is better:
If Not String.IsNullOrEmpty(Trim(textUserName.Text)) Then
textUserName.[ReadOnly] = True
End If

How do I correctly check DBNull in VB?

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.

Resources