Argument matching parameter 'text' cannot convert from 'DBNull' to 'String' - sql

Trying to import records from an Access database file and display the records in a listview (in Visual Basic). It works 50% of the time, but seems to crash stating:
An unhandled exception of type 'System.Reflection.AmbiguousMatchException' occurred in Microsoft.VisualBasic.dll
Additional information: Overload resolution failed because no Public 'Add' can be called with these arguments:
'Public Overrides Function Add(text As String) As System.Windows.Forms.ListViewItem':
Argument matching parameter 'text' cannot convert from 'DBNull' to 'String'.
'Public Overrides Function Add(value As System.Windows.Forms.ListViewItem) As System.Windows.Forms.ListViewItem':
Argument matching parameter 'value' cannot convert from 'DBNull' to 'ListViewItem'.
The code in question is the following:
ds.Clear()
LVResults.Items.Clear()
con.ConnectionString = dbProvider & dbSource
con.Open() 'Open connection to the database
sqlstatement = "SELECT * FROM records WHERE checkoutdate is NULL"
da = New OleDb.OleDbDataAdapter(sqlstatement, con)
da.Fill(ds, "allmembers") 'Fill the data adapter
con.Close()
Dim recordCount, x As Short
recordCount = 0
x = 0
recordCount = ds.Tables("allmembers").Rows.Count
With ds.Tables("allmembers")
Do Until x = recordCount
LVResults.Items.Add(.Rows(x).Item(0))
LVResults.Items(x).SubItems.Add(.Rows(x).Item(1))
LVResults.Items(x).SubItems.Add(.Rows(x).Item(2))
LVResults.Items(x).SubItems.Add(.Rows(x).Item(3))
LVResults.Items(x).SubItems.Add(.Rows(x).Item(4))
x = x + 1
Loop
End With
Knowing me it's something really obvious but do appreciate the help :)
The most annoying this is that it works sometimes, but others it'll throw up the error.

The error message is pretty self-explanatory to be honest - some of the fields contain null values, which VB won't auto-convert to empty strings or zeros. One solution would be to edit the SQL statement to explicitly avoid returning nulls:
SELECT IIf(Surname Is Null, '', Surname), IIf(Forename Is Null, '', Forename),
IIf(SomeIntField Is Null, 0, SomeIntField) FROM records WHERE CheckoutDate Is Null

Related

parameter has no default value vb.net

I'm getting the error System.Data.OleDb.OleDbException: 'Parameter #client_address has no default value.' but I have sent all the parameters needed.
cmd.Connection = cn
cmd.CommandText = "insert into invoice([invoice_date],[client_name],[client_company_name],[client_email],[client_contact_no],[client_address],[client_delivery_address],[total_basic_amount],[freight_rate],[delivery_rate],[advanced_amount],[pending_amount])
Values(#invoice_date,#client_name,#client_company_name,#client_email,#client_contact_no,#client_address,#client_delivery_address,#total_basic_amount,#freight_rate,#delivery_rate,#advanced_amount,#pending_amount)"
cmd.Parameters.AddWithValue("#invoice_date", datetime.Value)
cmd.Parameters.AddWithValue("#client_name", client_name.Text)
cmd.Parameters.AddWithValue("#client_company_name", company_name.Text)
cmd.Parameters.AddWithValue("#client_email", email.Text)
cmd.Parameters.AddWithValue("#client_contact_no", contact_no.Text)
cmd.Parameters.AddWithValue("#client_address", address.Text)
cmd.Parameters.AddWithValue("#client_delivery_address", delivery_address.Text)
cmd.Parameters.AddWithValue("#total_basic_amount", total_basic_amount.Text)
cmd.Parameters.AddWithValue("#freight_rate", freigh_rate.Text)
cmd.Parameters.AddWithValue("#delivery_rate", delivery_rate.Text)
cmd.Parameters.AddWithValue("#advanced_amount", advance_received_amount.Text)
cmd.Parameters.AddWithValue("#pending_amount", total_pending_amount.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Invoice Stored")
I'm using accessdb in vb.net. and all variables has value nothing is empty. when I comment or remove client_address it start giving error on client_delivery_address.
Changes the way to create the parameter specifying the type and size, as in the example below:
cmd.Parameters.Add("#client_address", System.Data.OleDb.OleDbType.BSTR, 100);

Input string was not in correct format | decimal/integer to "NULL"

I've recently started learning .net and I wrote a basic sql connected data entry form. Almost all of my data types are integer or decimals. Sometimes I need to remain empty the textboxes and enter "NULL" data and I receive with this error "Input string was not in correct format".
How I can fix this error ? Key point; I don't want to enter "0" it must be "NULL" in sql server because I use some charts to track all of these data, so when there is data equal the "0" its ruined my charts. As far as I understand from my researches Tryparse is fit for it but I couldn't find any information to use it properly in .net.
I'll share my transformation code below.
Try
Dim command As New SqlCommand()
command.Parameters.Add("A", SqlDbType.Decimal).Value = Decimal.Parse(A)
command.Parameters.Add("B", SqlDbType.Int).Value = Integer.Parse(B)
command.Parameters.Add("C", SqlDbType.Decimal).Value = Decimal.Parse(C)
command.Parameters.Add("D", SqlDbType.Decimal).Value = Decimal.Parse(D)
command.Parameters.Add("E", SqlDbType.Decimal).Value = Decimal.Parse(E)
command.Parameters.Add("F", SqlDbType.Decimal).Value = Decimal.Parse(F)
command.Parameters.Add("G", SqlDbType.Int).Value = Integer.Parse(G)
command.Parameters.Add("H", SqlDbType.Int).Value = Integer.Parse(H)
c.CUD(command, sql)
list()
clear()
MessageBox.Show("Data Successfully Saved")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
command.Parameters.Add("strokeTB", SqlDbType.Decimal).Value = If(strokeTB.TextLength = 0, CObj(DBNull.Value), Decimal.Parse(strokeTB.Text))
This assumes that you have already validated the contents of the TextBox and it is guaranteed to either be empty or contain a valid Decimal value.
This If operator is similar to the old IIf function but it's better because it short-circuits, i.e. the third argument operand is only evaluated if the first operand is False. Because IIf is a function, it evaluates all three arguments first, so Decimal.Parse would still be called and it would fail. Using If, Decimal.Parse will only be called if there is text to parse.

Conversion from type 'DBNull' to type 'String' is not valid vb.net

While using the given below code showing one error. The error is: "Conversion from type 'DBNull' to type 'String' is not valid." Help me to find a proper solution. Thank you.
Code:
cmd2.CommandText = "SELECT [first_name]+' ' +[middle_name]+' ' + [last_name] AS NAME, [staff_id] FROM [staff_profile]"
sdr2 = cmd2.ExecuteReader
While sdr2.Read
drop1l.Items.Add(New ListItem(sdr2("name"), sdr2("staff_id"))) // error popup here
End While
sdr2.Close()
You should try like this:
If Not IsDBNull(dt.Rows(0)("name")) Then
sdr2.Value = dt.Rows(0)("name")
End If
If Not IsDBNull(dt.Rows(1)("staff_id")) Then
sdr2.Value = dt.Rows(1)("staff_id")
End If
or a dirty fix like this:
drop1l.Items.Add(New ListItem(sdr2("name").ToString(), sdr2("staff_id").ToString()))
It means that one of the values you have received, is null, and it cannot be casted to string. You could implement a function that does the casting for you (and checks if a value is dbnull or nothing), something in the line of:
Function GetStringValue(value as Object) as String
if value is Nothing or IsDBNull(value)then
Return String.Empty
End If
Return DirectCast(value, GetType(String))
End Function
and then you could do
drop1l.Items.Add(new ListItem(GetStringValue(sdr2("name")), GetStringValue(sdr2("staff_id")))
You are getting this error because either sdr2("name") or sdr2("staff_id") is null. you can avoid it in two ways:
1.
drop1l.Items.Add(New ListItem(sdr2("name").Tostring(), sdr2("staff_id").Tostring()))
2. or check for null in the query
try like this also
dt.Rows(0)("name").ToString()

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))

Insert date time into database

I'm using OleDbCommand to insert a Date/Time field using parameters, and getting an exception stating that "Data type mismatch in criteria expression."
I've identified the parameter causing my issue, and executing the following code causes my error:
insertCmd.CommandText = "INSERT INTO myTable ([ParameterName]) VALUES (?)"
insertCmd.Parameters.AddWithValue("#ParameterName", Now)
insertCmd.Connection = _connection
return insertCmd.ExecuteNonQuery()
Checking out the parameter that's causing the issue, I get the following for parameter {#ParameterName}
ChangeID: 1
DbType: DateTime {6}
Direction: Input {1}
IsNullable: False
Offset: 0
OleDbType: DBTimeStamp {135}
ParameterName: "#ParameterName"
Precision: 0
PrecisionInternal: 0
Scale: 0
ScaleInternal: 0
Size: 0
SourceColumn: ""
SourceColumnNullMapping: False
SourceVersion: Current {512}
Value: #10/9/2014 11:26:15 AM# {Date}
It appears to be recognized as DbType DateTime and the Object inserted into the parameters is a Date object, but It still is telling me that there is a problem with the data type.
Most of the places I've seen this issue have been trying to write a string into a Date/Time field, which I am definitely not doing.
Try using just the Date value since it appears that your database field is a date value only (I'm guessing):
insertCmd.Parameters.AddWithValue("#ParameterName", Now.Date)
or it could be that OleDB is just confused by the type, so set it yourself:
Dim p As New OleDbParameter("#parameterName", OleDbType.Date)
p.Value = Now
insertCmd.Parameters.Add(p)