OverFlowException on Executescalar on vb.net - sql

I'm working in asp.net with vb.net and in the backend I'm trying to select something from the database.
But whenever I ask to execute the query it gives an error which says 'OverflowException Ocuured'. The query that is made works perfectly in my SQL Manager tool. Any ideas what can be the problem.
(it gives the problem on the line under 'try' so the 'returnedId = com.ExecuteScalar' line)
Function selectEIDCardnumber(ByVal name As String) As Integer
Dim con As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("testdatabase").ConnectionString)
Dim selecter As String = "SELECT EIDCardNumber FROM [dbo].[_User] where DisplayName = #name"
Dim com As New SqlCommand(selecter, con)
com.Parameters.AddWithValue("#name", name)
con.Open()
Dim returnedId As Integer = 0
Try
returnedId = com.ExecuteScalar
Catch ex As Exception
Response.Redirect("oops.aspx")
End Try
con.Close()
Return returnedId
End Function

The result of com.ExecuteScalar is larger than the max int value.
Int32.TryParse(com.ExecuteScalar, returnedId)

By defining your returnedId and Function As type Integer you are telling VB that the value will be a whole number between -2,147,483,648 and 2,147,483,647. Assuming the data in your database is correct, the solution is to change the returnedId and Function types to Int64, which holds numbers up to 9,223,372,036,854,775,807.

If you're sure that the EIDCardNumber column is an integer type column then try changing Dim returnedId As Integer = 0 into Dim returnedId As Long = 0 and if the problem persists try changing the value of selecter to "SELECT top 1 EIDCardNumber FROM [dbo].[_User] where DisplayName = #name"

Related

Converting Empty String to NULL Double

I have spent much of the day trying to find an answer for this one. I figured it would be easy but nothing is specific to what I am trying to do. So I hope someone can help.
I am bringing values over from one system to another. I have a few fields that come over as strings but they need to go into the new system as DOUBLE. The problem occurs when there are empty strings ("") and it is trying to store this as double. I have tried EVERYTHING.
dbnull.value
Double.TryParse
CDBL()
Double?
VAL()
etc...cannot get this to work and I am not sure why.
so here is the code:
Dim specvertclr As String = dt23.Rows(0).ItemArray.GetValue(38).ToString()
then when I insert this into my database I get the error because the field type is NUMERIC and I am trying to insert ""
I did have this working:
Dim specvertclr As String
If dt23.Rows(0).ItemArray.GetValue(38).ToString() = "" Then
specvertclr = CStr(0)
Else
specvertclr = dt23.Rows(0).ItemArray.GetValue(38).ToString()
End If
But the problem with this is it inserts a 0 value and 0 is not the same as NULL. I want the NUMERIC field in my destination database (SQLCE) to be EMPTY when the string is empty from the source database.
Any help?
This is what I tried:
Dim specvertclr As Nullable(Of Double) = CType(dt23.Rows(0).ItemArray.GetValue(38).ToString(), Double?)
and then my insert is basic and the program throws an error before it even gets here. I know this part is correct.
Dim cmd2 As SqlCeCommand = conn.CreateCommand()
cmd2.CommandText = "Insert into [Attr_Bridge] ([VERTCLR]) VALUES (?)"
With cmd2.Parameters
.AddWithValue("P1", specvertclr)
end with
You need to check the content of your string before adding it to the database
Dim specvertclr = dt23.Rows(0).ItemArray.GetValue(38).ToString()
....
Dim cmd2 As SqlCeCommand = conn.CreateCommand()
cmd2.CommandText = "Insert into [Attr_Bridge] ([VERTCLR]) VALUES (#P1)"
With cmd2.Parameters
.Add("#P1", SqlDbType.Float).Value = If(String.IsNullOrEmpty(specvertclr), DBNull.Value, CType(specvertclr, Object))
This turned out to be the answer .... Thank You Arminius for your linked article that lead me to right answer ... Thank you Steve for your time and help!
Dim specvertclr As String = dt23.Rows(0).ItemArray.GetValue(38).ToString()
Dim oerrorspec As Object = System.DBNull.Value
If specvertclr <> Nothing Then oerrorspec = specvertclr
and then in the parameters section I used this
.Add(New SqlCeParameter("#P41", oerrorspec))
I came across this question because I had the same issue. I was creating an app and one of the inputs was optional and I didn't want users to worry about putting zero so they don't receive an error. So my question was how to convert "" string to double? I came up with the below:
Dim Nontaxable As Double
If txtNontaxable.Text IsNot "" Then
Nontaxable = CDbl(txtNontaxable.Text)
Else
txtNontaxable.Text = 0
End If
if the string isn't blank, it will be converted fine, if its blank, it will be replaced with zero, and then it will be converted fine. Hope this helps anyone had the same issue.

Too many arguments to '' in VB.net

I'm trying to save from list field that have more than one data on it, how to save all of it at once?
I've try this code
Dim detail As New Detail
Dim detailBr As New DetailBridge
Dim i As Integer
For i = 0 To lstProduct.Items.Count - 1
detail = detailBr.Insert(Convert.ToInt32(ddlGroup.SelectedValue), lstProduct.Items(i).Value) 'error was here
Next
but I got an error in lstProduct.Items(i).Value the error said
Too many arguments to '...'
I'm not sure what the error is.
can anyone help? Thanks for advice.
UPDATE : detailBr is class and the code is
Public Function Insert(ByVal GroupID As Integer, ByVal ProductID As String) As Boolean
Dim iResult As Integer
Dim arrColumn() As String = {"GroupID", "ProductID"}
Dim arrValue() As Object = {GroupID, ProductID}
oConn.Open()
Dim SQLString As String = GenInsert("DetailGroup", arrColumn, arrValue)
Try
iResult = SCommand.Execute(SQLString, oConn)
Catch ex As Exception
Throw ex
Finally
oConn.Close()
End Try
If iResult > 0 Then
Return True
Else
Return False
End If
End Function
The problem here is with the GenInsert Function. Its last two arguments are arrays.
Dim arrColumn() As String = {"GroupID", "ProductID"}
Dim arrValue() As Object = {GroupID, ProductID}
Dim SQLString As String = GenInsert("DetailGroup", arrColumn, arrValue)
A procedure can define only one parameter array, and it must be the last parameter in the procedure definition. MSDN
In simple words you can have only one parameter as array in GenInsert function either arrColumn or arrValue
However, to solve your current problem you can use two dimensional array as parameter as in passing-two-dimensional-array-through-functions and MSDN: Arrays as Return Values and Parameters

Specified cast is not valid in vb.net

Getting this error when assigning an integer variable to a value coming back from a SQL stored procedure that may at times contain a NULL.
System.InvalidCastException: Specified cast is not valid.
Code snippet:
Dim iUserId As Nullable(Of Integer)
' Get the UserId associated to the server.
.CommandType = Data.CommandType.StoredProcedure
.CommandText = "SelectUserIdByServerId"
.Parameters.Clear()
.Parameters.AddWithValue("#ServerId", Request("serverid"))
' Returns back 1 column.
iUserId = .ExecuteScalar()
I though that if I have: Dim iUserId As Nullable(Of Integer), that it should not have a problem with it.
ExecuteScalar() returns Object which is an integer or DbNull value.
So you need to write it like this:
Dim tmp As Object = .ExecuteScalar()
iUserId = if(Convert.IsDbNull(tmp), new integer?(), directcast(tmp, integer))

"Format Exception was Unhandeled" in vb.net

What is wrong here in the code
Dim sReaderList As String
sReaderList = New System.String(vbNullChar, 1024)
Dim x As Integer = Convert.ToInt32(sReaderList)
When debug it produce "Format Exception was Unhandeled"
and Input string was not in a correct format in vb.net
Convert.ToInt32 throws a format exception when the given string either contains invalid characters or is an empty string (note that Nothing would be ok, but '' is not).
As mentioned by Marco you have to catch the exception or be sure that the string contains only valid numerical characters (and vbNullChar is not one of those). Also: if the possibility of empty strings arises, you have to manually check for this or again catch the exception.
The error is happening because you are trying to convert something to an integer which cant be converted so it is throwing an exception.
There are two approaches you can use to solve this problem:
1) Wrap it all in a try / catch block
Dim sReaderList As String
sReaderList = New System.String(vbNullChar, 1024)
Try
Dim x As Integer = Convert.ToInt32(sReaderList)
Catch ex As Exception
End Try
2) use the Tryparse method
Dim i As Integer
Dim s As String = String.Empty
Dim result As Boolean
result = Integer.TryParse(s, i)
If (result) Then
'Code here
End If
You're trying to convert a string filled with non digits to integer... so you're getting the error.
Did you expect something different? Why?
If you want to catch the exception, you could do
Dim sReaderList As String
sReaderList = New System.String(vbNullChar, 1024)
Try
Dim x As Integer = Convert.ToInt32(sReaderList)
Catch
' Manage the error here
End Try
Note, just for example, that if you insert a digit at the beginning of the string, the error disappear.
sReaderList = "1" & sReaderList
Dim x As Integer = Convert.ToInt32(sReaderList) ' This works

handling dbnull data in vb.net

I want to generate some formatted output of data retrieved from an MS-Access database and stored in a DataTable object/variable, myDataTable. However, some of the fields in myDataTable cotain dbNull data. So, the following VB.net code snippet will give errors if the value of any of the fields lastname, intials, or sID is dbNull.
dim myDataTable as DataTable
dim tmpStr as String
dim sID as Integer = 1
...
myDataTable = myTableAdapter.GetData() ' Reads the data from MS-Access table
...
For Each myItem As DataRow In myDataTable.Rows
tmpStr = nameItem("lastname") + " " + nameItem("initials")
If myItem("sID")=sID Then
' Do something
End If
' print tmpStr
Next
So, how do i get the above code to work when the fields may contain dbNull without having to check each time if the data is dbNull as in this question?
The only way that i know of is to test for it, you can do a combined if though to make it easy.
If NOT IsDbNull(myItem("sID")) AndAlso myItem("sID") = sId Then
'Do success
ELSE
'Failure
End If
I wrote in VB as that is what it looks like you need, even though you mixed languages.
Edit
Cleaned up to use IsDbNull to make it more readable
I got tired of dealing with this problem so I wrote a NotNull() function to help me out.
Public Shared Function NotNull(Of T)(ByVal Value As T, ByVal DefaultValue As T) As T
If Value Is Nothing OrElse IsDBNull(Value) Then
Return DefaultValue
Else
Return Value
End If
End Function
Usage:
If NotNull(myItem("sID"), "") = sID Then
' Do something
End If
My NotNull() function has gone through a couple of overhauls over the years. Prior to Generics, I simply specified everything as an Object. But I much prefer the Generic version.
You can also use the Convert.ToString() and Convert.ToInteger() methods to convert items with DB null effectivly.
A variation on Steve Wortham's code, to be used nominally with nullable types:
Private Shared Function GetNullable(Of T)(dataobj As Object) As T
If Convert.IsDBNull(dataobj) Then
Return Nothing
Else
Return CType(dataobj, T)
End If
End Function
e.g.
mynullable = GetNullable(Of Integer?)(myobj)
You can then query mynullable (e.g., mynullable.HasValue)
Microsoft came up with DBNull in .NET 1.0 to represent database NULL. However, it's a pain in the behind to use because you can't create a strongly-typed variable to store a genuine value or null. Microsoft sort of solved that problem in .NET 2.0 with nullable types. However, you are still stuck with large chunks of API that use DBNull, and they can't be changed.
Just a suggestion, but what I normally do is this:
All variables containing data read from or written to a database should be able to handle null values. For value types, this means making them Nullable(Of T). For reference types (String and Byte()), this means allowing the value to be Nothing.
Write a set of functions to convert back and forth between "object that may contain DBNull" and "nullable .NET variable". Wrap all calls to DBNull-style APIs in these functions, then pretend that DBNull doesn't exist.
You can use the IsDbNull function:
If IsDbNull(myItem("sID")) = False AndAlso myItem("sID")==sID Then
// Do something
End If
If you are using a BLL/DAL setup try the iif when reading into the object in the DAL
While reader.Read()
colDropdownListNames.Add(New DDLItem( _
CType(reader("rid"), Integer), _
CType(reader("Item_Status"), String), _
CType(reader("Text_Show"), String), _
CType( IIf(IsDBNull(reader("Text_Use")), "", reader("Text_Use")) , String), _
CType(reader("Text_SystemOnly"), String), _
CType(reader("Parent_rid"), Integer)))
End While
For the rows containing strings, I can convert them to strings as in changing
tmpStr = nameItem("lastname") + " " + nameItem("initials")
to
tmpStr = myItem("lastname").toString + " " + myItem("intials").toString
For the comparison in the if statement myItem("sID")=sID, it needs to be change to
myItem("sID").Equals(sID)
Then the code will run without any runtime errors due to vbNull data.
VB.Net
========
Dim da As New SqlDataAdapter
Dim dt As New DataTable
Call conecDB() 'Connection to Database
da.SelectCommand = New SqlCommand("select max(RefNo) from BaseData", connDB)
da.Fill(dt)
If dt.Rows.Count > 0 And Convert.ToString(dt.Rows(0).Item(0)) = "" Then
MsgBox("datbase is null")
ElseIf dt.Rows.Count > 0 And Convert.ToString(dt.Rows(0).Item(0)) <> "" Then
MsgBox("datbase have value")
End If
I think this should be much easier to use:
select ISNULL(sum(field),0) from tablename
Copied from: http://www.codeproject.com/Questions/736515/How-do-I-avoide-Conversion-from-type-DBNull-to-typ
Hello Friends
This is the shortest method to check db Null in DataGrid and convert to string
create the cell validating event and write this code
If Convert.ToString(dgv.CurrentCell.Value) = "" Then
CurrentCell.Value = ""
End If
This is BY FAR the easiest way to convert DBNull to a string.
The trick is that you CANNOT use the TRIM function (which was my initial problem) when referring to the fields from the database:
BEFORE (produced error msg):
Me.txtProvNum.Text = IIf(Convert.IsDBNull(TRIM(myReader("Prov_Num"))), "", TRIM(myReader("Prov_Num")))
AFTER (no more error msg :-) ):
Me.txtProvNum.Text = IIf(Convert.IsDBNull(myReader("Prov_Num")), "", myReader("Prov_Num"))
Simple, but not obvious.
DbNull.Value.Equals(myValue)
I hate VB.NET
For your problem, you can use following special workaround coding that only exists in VB.Net.
Dim nId As Integer = dr("id") + "0"
This code will replace DBNull value contained in id column by integer 0.
The only acceptable default value is "0" because this expression must also be used when dr("id") is not NULL !
So, using this technic, your code would be
Dim myDataTable as DataTable
Dim s as String
Dim sID as Integer = 1
...
myDataTable = myTableAdapter.GetData() ' Reads the data from MS-Access table
...
For Each myItem As DataRow In myDataTable.Rows
s = nameItem("lastname") + " " + nameItem("initials")
If myItem("sID") + "0" = sID Then
' Do something
End If
Next
I have tested this solution and it works on my PC on Visual Studio 2022.
PS: if sID can be equal to 0 and you want to do something distinct when dr("sID") value is NULL, you must also adept you program and perhaps use Extension as proposed at end of this answer.
I have tested following statements
Dim iNo1 As Integer = dr("numero") + "0"
Dim iNo2 As Integer = dr("numero") & "0" '-> iNo = 10 when dr() = 1
Dim iNo3 As Integer = dr("numero") + "4" '-> iNo = 5 when dr() = 1
Dim iNo4 As Integer = dr("numero") & "4" '-> iNo = 14 when dr() = 1
Dim iNo5 As Integer = dr("numero") + "" -> System.InvalidCastException : 'La conversion de la chaîne "" en type 'Integer' n'est pas valide.'
Dim iNo6 As Integer = dr("numero") & "" -> System.InvalidCastException : 'La conversion de la chaîne "" en type 'Integer' n'est pas valide.'
Dim iNo7 As Integer = "" + dr("numero") -> System.InvalidCastException : 'La conversion de la chaîne "" en type 'Integer' n'est pas valide.'
Dim iNo8 As Integer = "" & dr("numero") -> System.InvalidCastException : 'La conversion de la chaîne "" en type 'Integer' n'est pas valide.'
Dim iNo9 As Integer = "0" + dr("numero")
Dim iNo0 As Integer = "0" & dr("numero")
Following statements works also correctly
Dim iNo9 As Integer = "0" + dr("numero")
Dim iNo0 As Integer = "0" & dr("numero")
I recognize that is a little tricky.
If trick are not your tips, you can also define an Extension so that following code works.
Dim iNo = dr.GetInteger("numero",0)
where GetInteger() code can be following
Module Extension
'***********************************************************************
'* GetString()
'***********************************************************************
<Extension()>
Public Function GetString(ByRef rd As SqlDataReader, ByRef sName As String, Optional ByVal sDefault As String = "") As String
Return GetString(rd, rd.GetOrdinal(sName), sDefault)
End Function
<Extension()>
Public Function GetString(ByRef rd As SqlDataReader, ByVal iCol As Integer, Optional ByVal sDefault As String = "") As String
If rd.IsDBNull(iCol) Then
Return sDefault
Else
Return rd.Item(iCol).ToString()
End If
End Function
'***********************************************************************
'* GetInteger()
'***********************************************************************
<Extension()>
Public Function GetInteger(ByRef rd As SqlDataReader, ByRef sName As String, Optional ByVal iDefault As Integer = -1) As Integer
Return GetInteger(rd, rd.GetOrdinal(sName), iDefault)
End Function
<Extension()>
Public Function GetInteger(ByRef rd As SqlDataReader, ByVal iCol As Integer, Optional ByVal iDefault As Integer = -1) As Integer
If rd.IsDBNull(iCol) Then
Return iDefault
Else
Return rd.Item(iCol)
End If
End Function
End Module
These methods are more explicitely and less tricky.
In addition, it is possible to define default values other than ZERO and also specific version as GetBoolean() or GetDate(), etc ...
Another possibility is to report SQL default conversion in SQL command using COALESCE SQL command !