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
Related
We recently migrated a very old site to a new server and are running into an odd issue. There is a simple if statement which should and did on old server read as true but it is not and not sure why. The statement is below. When I write out invflag it is equal to 1 which is what I would expect.
'does not trigger as true so iChk remains = ""
iChk = ""
if invflag = True then
iChk = "checked"
end if
'Works as expected
iChk = ""
if invflag = "1" then
iChk = "checked"
end if
'works as expected
iChk = ""
if invflag = 1 then
iChk = "checked"
end if
I know we can simply fix this as you can see but we have these types of statements littered throughout the code and if there is something with the server or database we can set that would be ideal and thought I would check.
Simply casting to CBool should do the trick for all cases:
If CBool(invflag) = True Then
iChk = "checked"
End If
or better
If CBool(invflag) Then
iChk = "checked"
End If
It turned out that during the migration from MSSQL to Mysql it converted the Bit fields to TinyInt. Once we changed the fields back to Bit the if statements worked as they did before.
We have a requirement where we have rules stored in a database table and from those rules we need to validate certain attributes at runtime.
The Table below depicts similar structure from where we will pull the Attribute Name and their respective rules to be evaluated based on the Rule_ID.
Example: If I want to validate attribute FirstName I need to check that FirstName attribute should not be null and must contain some value. If this is attribute is not having any data an error needs to be thrown against this attribute.
RULE_ID ATTRIBUTE_NAME ATTRIBUTE_RULE
ABC123 FirstName <> NULL
XYZ345 LastName <> NULL
GHI654 Age <>NULL
POC123 DateOfBirth < Sysdate
QWE675 BloodGroup = A+ve
JKL987 City <> London
IUK134 Occupation = NULL
As the Rules stored in the database will be in Varchar i.e. String, how can we convert these rules which are in string and validate the attribute in the code using vb.net?
Kindly help me regarding this.
I had something similar to this although you will need to adapt as you see fit.
Basically I created a series of functions which returned a boolean result
e.g. a Function to test for not blank...
Protected Function CheckNotBlank(value As String) as Boolean
If value <> "" then
Return True
Else
Return False
End If
End Function
a Function to test for Is less than numericvalue...
Protected Function CheckIsLessThan(value As Integer, compareToValue As Integer) As Boolean
If value < compareToValue Then
Return True
Else
Return False
End If
End Function
Then you could have a series of checks....
Dim ValidFlag as Integer = 0
Dim ErrorStack as New StringBuilder
If CheckNotBlank(MyValueToCheck) = False Then
ValidFlag += 1
ErrorStack.Append("MyValueToCheck is Blank ").Append(vbCrLf)
End If
If CheckIsLessThan(CheckIntegerValue, CompareToIntegerValue) = False Then
ValidFlag += 1
ErrorStack.Append("CheckIntegerValue is greater than CompareToIntegerValue ").Append(vbCRLF)
End If
If CheckNotBlank(AnotherValueToCheck) = False Then
ValidFlag += 1
ErrorStack.Append("AnotherValueToCheck is Blank ").Append(vbCrLf)
End If
......
If ValidFlag > 0 Then
'We have errors
End If
You would need to create and adapt your functions to suite. Hope that Helps!
Is it possible to check if a named field is within a record set?
EG id, field1, field2, field3 have been selected. Is it possible for VBScript to detect if field2 has been selected. I am also hoping this is possible without looping
Please assume I dont know, nor can see the actual SELECT. I need to detect this after the query has been executed.
This is how its done using a loop, I am also hoping this is possible without looping:
dim rs,field,foundField
sql = "SELECT * from table;"
set rs = conn.execute(sql)
For Each field in rs.Fields
if field.Name = "someFieldName" then
foundField = true
exit for
else
foundField = false
end if
next
TYIA
I use a similar function (in VB6) to the one proposed by bfavaretto... I'm curious why the OP says it doesn't work?
Public Function FieldExists(ByVal rs As Recordset, ByVal fieldName As String) As Boolean
On Error GoTo merr
FieldExists = rs.Fields(fieldName).name <> ""
Exit Function
merr:
FieldExists = False
End Function
This function works for me... and it doesn't return false negatives as far as I know. Also, it appears to be faster than executing a loop for fields that are included in the collection; for fields that are actually missing, the execution times of both methods seems to be equivalent.
EDIT
For VBScript, the above function would look like this:
Function FieldExists(ByVal rs, ByVal fieldName)
On Error Resume Next
FieldExists = rs.Fields(fieldName).name <> ""
If Err <> 0 Then FieldExists = False
Err.Clear
End Function
And the code posted in the question would look like:
dim rs,field,foundField
sql = "SELECT * from table;"
set rs = conn.execute(sql)
foundField = FieldExists(rs, "someFieldName")
I think you need the loop. Found this on MSDN (emphasis mine):
Most of the ASP built-in objects provide collections. Collections are
data structures similar to arrays that store strings, numbers, objects
and other values. Unlike arrays, collections expand and contract
automatically as items are retrieved or stored. The position of an
item will also move as the collection is modified. You can access an
item in a collection by its unique string key, by its index (position)
in the collection, or by iterating through all the items in the
collection.
In any case, you could try this (untested):
dim rs,field,foundField
sql = "SELECT * from table;"
set rs = conn.execute(sql)
if rs.Fields("someFieldName") then
' ... if this doesn't crash, it may return
' false negatives for columns containing null or 0
end if
This question has been asked long time ago on serverfault but no working awnser. I'm hoping somebody has encountered it and found a solution since then.
Example:
<%
Response.Write True
Response.Write "<hr>"
Response.Write "test:" & True
%>
Output:
True
--------------
test:Waar
As you can see, as soon as you combine the output, its turned into a local string ('Waar' is dutch for true). I need it to stay "True".
How can I change this? I dont mind putting some code at the beginning of the pages, but I cannot change all instances of True in the entire code. So creating a function like below to return the correct string wont do.
Function PB(pVal)
If pVal Then
PB = "true"
Else
PB = "false"
End If
End Function
Strange, I cannot get my IIS to output a boolean value in my local language no matter which locale is set.
Did you find this KB article already?
There is a description of a registry setting that could do the trick:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\OLEAUT
I don't want to mess with my production server, so I didn't try this yet.
FIRST ANSWER:
You could 'trick' VB to use your own functions. If you add these functions to the top of your page, VB will prefer these over the builtin ones, in this case CStr and Trim. Maybe this helps.
Function PB(pVal)
If pVal Then
PB = "true"
Else
PB = "false"
End If
End Function
Function CStr(pVal)
CStr = PB(pVal)
End Function
Function Trim(pVal)
Trim = PB(pVal)
End Function
Output:
True
--------------
test:true
--------------
test:true
--------------
test:true
I do something like this, but currently don't have a machine to test your case:
<%
Response.Write FormatDateTime(Now) & "<br />"
oldLocale = SetLocale(1026) 'Bulgarian
Response.Write FormatDateTime(Now) & "<br />"
SetLocale oldLocale
Response.Write FormatDateTime(Now) & "<br />"
%>
... from another SO question, it looks the above doesn't work.
What hapopens if you try these:
Response.Write "test:" & CStr(True)
or
Response.Write "test:" & Trim(True)
with or w/o SetLocale?
that is just like string concatenation works in vbscript.
from the vbscript language reference:
"Whenever an expression is not a string, it is converted to a String
subtype. If both expressions are Null, result is also Null. However,
if only one expression is Null, that expression is treated as a
zero-length string ("") when concatenated with the other expression.
Any expression that is Empty is also treated as a zero-length string."
If the SetLocale didn't work, then I think your best bet is to create a function.
Function TF(B)
If B Then
TF = "True"
Else
TF = "False"
End If
End Function
Then instead of saying this:
Response.Write "test:" & True
You'd say this:
Response.Write "test:" & TF(True)
You could try setting Response.LCID or Session.LCID to 1033 at the beginning of your page, but this also influences how others things (likes dates and currency variables) are displayed.
1033 is the Locale Id for the US
Attempt 2:
<%
arr=Array("False","True")
Response.Write True
Response.Write "<br /><br />"
Response.Write "" & arr( abs(True) ) & "<br />"
Response.Write "" & arr( abs(False) ) & "<br />"
%>
I found a solution if you dont mind changing regional settings to united states one. It involves changing the registry. This has been tested in windows 7 spanish and now it give native True/False instead of Verdadero/Falso.
Navigate to HKEY_USERS/.Default/Control Panel/International and take a nice picture with your phone in case you mess things up. you can also make a backup of the registry keys by clicking "international" and then File/export
Open a notepad and paste this inside (you can alternatively change values by hand one by one in the registry):
----------------- paste what is below this line -------------
Windows Registry Editor Version 5.00
[HKEY_USERS\.DEFAULT\Control Panel\International]
"Locale"="00000409"
"LocaleName"="en-US"
"s1159"=""
"s2359"=""
"sCountry"="United States"
"sCurrency"="$"
"sDate"="/"
"sDecimal"="."
"sGrouping"="3;0"
"sLanguage"="ENU"
"sList"=","
"sLongDate"="dddd, MMMM dd, yyyy"
"sMonDecimalSep"="."
"sMonGrouping"="3;0"
"sMonThousandSep"=","
"sNativeDigits"="0123456789"
"sNegativeSign"="-"
"sPositiveSign"=""
"sShortDate"="M/d/yyyy"
"sThousand"=","
"sTime"=":"
"sTimeFormat"="h:mm:ss tt"
"sShortTime"="h:mm tt"
"sYearMonth"="MMMM, yyyy"
"iCalendarType"="1"
"iCountry"="1"
"iCurrDigits"="2"
"iCurrency"="0"
"iDate"="0"
"iDigits"="2"
"NumShape"="1"
"iFirstDayOfWeek"="6"
"iFirstWeekOfYear"="0"
"iLZero"="1"
"iMeasure"="1"
"iNegCurr"="0"
"iNegNumber"="1"
"iPaperSize"="1"
"iTime"="0"
"iTimePrefix"="0"
"iTLZero"="0"
[HKEY_USERS\.DEFAULT\Control Panel\International\Geo]
"Nation"="244"
----------------- do not paste this line -------------
Save it as english.reg (or whatever.reg)
Double click it.
I didnt have to restart my computer for changes to take effect.
-------- UPDATE ----------
Does not work. If I make a blank asp page with this: <%=isnumeric(6)%> it answers True (in english) but as soon as I concatenate a True in a string it becames Verdadero again.
I was "caught" too with this "issue".
Indeed, this is not an issue :
THE PROBLEM (EXAMPLE)
I had the same problem when using a boolean data in a SQL Statement.
On my French server, my SQL statement was the following :
<%
'Set my boolean value
Dim myBoolean
myBoolean = True
'Set my SQL Statement
Dim MySQLStatement
MySQLStatement = "SELECT * FROM MyTable WHERE MyBooleanField = " & myBoolean
'=> Here, as MySQLStatement is a STRING, the boolean data was "converted/rendered" as a localized string. So that leads to this output :
'=> SELECT * FROM MyTable WHERE MyBooleanField = Vrai
'Obviously, that SQL Statement is incorrect, because the SQL Engine does NOT understand what is the "Vrai" word - It should be "True" instead.
%>
THE EXPLANATIONS :
It does not matter which regional settings are set on your Windows System : Nothing happens to the underlying data. A boolean data type is STILL a BOOLEAN, in English, or French, or German, Russian, Thai, ..or any language you want.
The fact is that the data is simply being RENDERED as a localized STRING (like dates).
THE SOLUTION
After a lot of reading over forums threads, the solution is not to change regional settings on the Windows system, nor changing Registry keys, nor changing Session.LCID, ...
The absolute and code-only solution is to convert the Boolean value (True|False) to an Integer (0|1). Then, this Integer will be safely usable in a string, and will remain (0|1).
Here is the safe way to use/convert/render a Boolean value in a non-localized form : Use an Integer value.
<%
'Set my boolean value
Dim myBoolean
myBoolean = True
'Set my SQL Statement
Dim MySQLStatement
MySQLStatement = "SELECT * FROM MyTable WHERE MyBooleanField = " & BoolToInt(myBoolean)
'=> Here, as MySQLStatement is a STRING, and as the boolean data was previously "converted/rendered" as an integer, we got this correct SQL Statement :
'=> SELECT * FROM MyTable WHERE MyBooleanField = 1
'This SQL Statement is correct, as the SQL Engine DOES understand that 1 is a boolean.
'This Function Returns an INTEGER value based on a BOOLEAN value
Function BoolToInt(v)
'INPUT:
'v Boolean value
'OUTPUT:
'Integer (0|1)
Dim b_OUT
b_OUT = v
'If the Input value is a "True" boolean value (in any language)
if (b_OUT = True) then
BoolToInt = cint(1)
'If the Input value is a "False" boolean value (in any language)
elseif (b_OUT = False) then
BoolToInt = cint(0)
end if
End Function 'BoolToInt
%>
I really hope it save your day !
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.