I get the Conversion from type 'DBNull' to type 'Integer' is not valid." error on the line "Dim avgObject As string = Cstr(avgCom.ExecuteScalar())
The command works when the where module_ID='" & moduleSelect & "' statement is removed and I do not know how to fix this, can anyone help?
Dim moduleSelect As String = moduleRadio.SelectedValue
Using connection As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Using avgCom As New SqlCommand("SELECT AVG(exam) FROM completed_module where module_ID='" & moduleSelect & "' ", _
connection)
connection.Open()
Dim avgObject As Integer = CInt(avgCom.ExecuteScalar())
Dim averageVar As String
averageVar = avgObject.ToString
avgLabel.Text = averageVar
End Using
I believe you are looking for something like this, first checking if it is dbnull:
Dim moduleSelect As String = moduleRadio.SelectedValue
Using connection As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Using avgCom As New SqlCommand("SELECT AVG(exam) FROM completed_module where module_ID='" & moduleSelect & "' ", _
connection)
connection.Open()
Dim result = avgCom.ExecuteScalar()
If IsDBNull(result) then return
Dim avgObject As Integer = CInt(result)
Dim averageVar As String
averageVar = avgObject.ToString
avgLabel.Text = averageVar
End Using
DBNull means that the record in the database does not contain a value for the column. So basically you are trying to convert "nothing" into a number.
What do you want your program to do? Skip the row? Use a default value instead?
If the command really "works" if you remove a statement from the command, I suggest you simply remove it.
Use Convert.ToString instead. Directcast as string does not work for Null/Nothing
UPDATE
Problem happens whenever you do not receive any results.
I tested, so CStr to Convert.ToString works for DBNUll, but CInt and Convert.ToIntXX still throws an eception.
You can use
Dim scalarResult = avgCom.ExecuteScalar()
If Convert.IsDBNull(scalarResult) then
avgObject = 0
Else
avgObject = Convert.toInt32(scalarResult)
End If
Error :Conversion from type 'DBNull' to type 'Integer' is not valid.
This error Occurs because your query return a NULL value.. you can manage the NULL value by using the Below code..
Try like below it will help you...
connection.Open()
Dim result As String = avgCom.ExecuteScalar().ToString()
Dim avgObject As Integer = If(result = "", 0, CInt(result))
Probably this fails because there is a value missing. (i.e. NULL)
But it might work if you default to 0 if a row with NULL was encountered:
SELECT AVG(ISNULL(exam,0)) FROM completed_module where module_ID=
Otherwise make sure your table does not include NULL-values for that column:
UPDATE completed_module SET exam = 0 WHERE exam IS NULL
(maybe constraint it so it may not have future NULL-Values also ;))
EDIT: this assumes that you can actually have an average value for every row, even those where the column you access is NULL, in that case i would assume NULL does not add anything to your average value (which the other rows that share that ID might) so I default it to 0
Related
When I try to update my databse table, what should I do?
Why am I getting this error?
it's because mismatched datatype inserted to your columns
change update query to be like this
update Hasil_Rml_Hallo_Bro SET Nilai_Error=" & Label3.text & " WHERE ID=" & label4.text
remove the "'" apostrophe letter
Make sure that your column in your database has the same data type which you are inserting into it.
Always use Parameters
Dim query As String = "update Hasil_Rml_Hallo_Bro SET Nilai_Error= #Error WHERE ID=#Id"
Using connection As New OleDbConnection(connectionString)
Using command As New OleDbCommand(query, connection)
Dim errorParameter As New OleDbParameter With
{
.ParameterName = "#Error",
.OleDbType = OleDbType.VarChar, // Or what is correct type in database
.Value = Label3.text
}
Dim idParameter As New OleDbParameter With
{
.ParameterName = "#Id",
.OleDbType = OleDbType.Integer, // Or what is correct type in database
.Value = Integer.Parse(label4.text) // Convert to correct type if needed
}
command.Parameters.Add(errorParameter, idParameter)
connection.Open()
command.ExecuteNonQuery()
End Using
End Using
Notice that you need put correct type for the parameter - same as column type you are using.
I am attempting to pull values from an SQL Server table from VB.NET.
On VB Form 1, the number from NoTable, Row 1, is pulled successfully, and Label1 is updated with the value.
Dim command As SqlCommand
Dim query As String = "SELECT Number FROM NoTable"
command = New SqlCommand(query, con)
con.Open()
Dim datareader As SqlDataReader = cmd.ExecuteReader()
If datareader.Read() Then
Label1.Text = datareader.GetValue(0)
End If
datareader.Close()
On VB Form 2 I am attempting to pull the value from the second row, using:
Dim query As String = "SELECT Number FROM NoTable"
command = New SqlCommand(query, con)
con.Open()
Dim datareader As SqlDataReader = cmd.ExecuteReader()
If datareader.Read() Then
Label1.Text = datareader.GetValue(1)
End If
datareader.Close()
However, this does not work, and the label is not updated with the value from the second row.
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll
Additional information: Index was outside the bounds of the array."
How would I go about fixing this, so that on Form 2, the value from Row 2 is pulled, and so forth?
Thank you.
Firstly, you only get one column back from the reader, but you are indexing the columns with that 0 or 1. So you should always pass 0 to GetValue.
To index the row instead, try this. Assign a form number to each form (first line in my example) and use that to determine which record to assign to the Label. There is probably a more efficient way to do this (not returning all the records before it) but this solution should fit in your environment.
' in form # 1
Dim formNumber = 1
Dim command As SqlCommand
Dim query As String = "SELECT Number FROM NoTable"
command = New SqlCommand(query, con)
con.Open()
Dim datareader As SqlDataReader = cmd.ExecuteReader()
Dim index = 0
While index < formNumber
If datareader.Read() AndAlso index = formNumber Then
Label1.Text = datareader.GetValue(0)
End If
index += 1
End While
datareader.Close()
See https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getvalue(v=vs.110).aspx
And another similar question in c# Access a specific row in DataReader
Another way is to just return the row you need in the first place, without iterating over the records on the client side. Assuming there is another column with an index which is in the same order as the row you want to return, called "ID"
' in form # 1
Dim formNumber = 1
Dim command As SqlCommand
Dim query As String =
"SELECT Number FROM " & _
" (SELECT Number, Row_Number() OVER (ORDER BY ID) AS RowNumber " & _
" FROM NoTable) AS Results " & _
" WHERE Results.RowNumber = " & formNumber.ToString()
command = New SqlCommand(query, con)
con.Open()
Dim datareader As SqlDataReader = cmd.ExecuteReader()
Label1.Text = datareader.GetValue(0)
datareader.Close()
See https://msdn.microsoft.com/en-us/library/ms186734.aspx
GetValue(1) does not exist, as this would refer to a second column in the select statement. You are only asking for [Number] which would be datareader.GetValue(0)
I have created a code to take data from one database and place it into a second database, the problem i am having currently is when a field in the database is null it returns an error
"Conversion type 'DBNULL' to type 'String' is not valid"
The code I am using is:
Dim ITN As String = ResultSet.Item( "ItemNumber")
Dim QN As String = ResultSet.Item( "QuoteNumber")
Dim ITD As String = ResultSet.Item( "ItemDescription")
Dim DET As String = ResultSet.Item( "Details")
Dim PR As String = ResultSet.Item("Price")
Hoping someone can assist with this one!!
You can use a ternary statement and check if the Item is null before casting it to a string.
Also in c# you could do something like this:
String value = ResultSet.Item("Price") as String;
The as will convert an invalid reference type to null automatically. For VB.NET:
VB.Net equivalent of C# "As"
I got tired of checking for DBNULL so i wrote a function for that. Depending on the type of database you are working with it really depends but, For efficiency, you'd probably want to use the StringBuilder class rather than string concatenation.
If you use a parameterized query see this link for a very basic introduction to using parameterized queries with Access, you would be able to directly insert the special DBNull value:
Dim myConnection As New OleDbConnection(DBConnection)
Dim Cmd As OleDbCommand = New OleDbCommand()
Cmd.CommandText = "INSERT INTO dbTable (ItemNumber, QuoteNumber, ItemDescription, Details, Price) VALUES (#ITN, #QN, #ITD, #DET, #PR)"
Cmd.Parameters.Add(New OleDbParameter("#ITN", OleDbType.VarChar)).Value = CheckDBNull(ITN)
Cmd.Parameters.Add(New OleDbParameter("#QN", OleDbType.VarChar)).Value = CheckDBNull(QN)
Cmd.Parameters.Add(New OleDbParameter("#ITD", OleDbType.VarChar)).Value = CheckDBNull(ITD)
Cmd.Parameters.Add(New OleDbParameter("#DET", OleDbType.VarChar)).Value = CheckDBNull(DET)
Cmd.Parameters.Add(New OleDbParameter("#PR", OleDbType.VarChar)).Value = CheckDBNull(PR)
DBConnection.Open()
Cmd.ExecuteNonQuery()
this is also good for avoiding nasty SQL Injection. Like I mentioned, depending on the database you are using you might have to use SqlParameter & SqlDbType vs. OleDbParameter & OleDbType but The CheckDBNull function could be a simple as the following:
Private Function CheckDBNull(ByVal s As String) As Object
If Not s Is Nothing And s.Length > 0 Then
Return s
Else
Return System.DBNull.Value
End If
End Function
I hope this helps. please note some of these parameters were just used as an example (myConnection, Cmd, dbTable) as you did not provide db info:
I have a SELECT statement for ListView and for ListBox even for DataGrid the only problem is that I can't display a result to my TextBox I just want to use:
The MAX() Function
I want to used MAX() because it says that it will return the larges value of the selected column, since I used INCREMENT to my ID MAX() Function is my one way to do it.
I used this codes to generate the ID:
Dim p1num As Integer = 0
p1num += 1
txtPNumber.Text = p1num.ToString("D4")
I try to understand your question and I think you should used this:
Try:
Dim querystring As String = "SELECT MAX(pIDNo) FROM (Name of your Table)"
Using connection As New SqlConnection("Data Source=(local);Initial Catalog=(Name of your DB);Persist Security Info=True;User ID=(Your User);Password=(Your Pass)")
Dim command As New SqlCommand(querystring, connection)
connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader
Dim value = String.Empty
While reader.Read
value = reader.GetString(0)
End While
txtPNumber.Text = Today.Year.ToString().Substring(2, 2) & Today.Month.ToString().PadLeft(2, "0") & (Integer.Parse(value.Substring(4, value.Length - 4)) + 1).ToString("D4")
End Using
Catch ex As Exception
txtPNumber.Text = Today.Year.ToString().Substring(2, 2) & Today.Month.ToString().PadLeft(2, "0") & num.ToString("D4")
End Try
Try to make a Private Sub with it and used it to the Form Load if you want to display it after the program run or on button if you want a trigger to display the ID that you want.
I used the following statement for a parameter.
.Parameters("#SearchValue").Value = TextBoxParentID.Text
for this query:
objSqlCommand.CommandText = "Select ID " & _
"From Parents " & _
"Where ID = #SearchValue"
ID is a SQL server numeric column but I get this error:
error converting nvarchar to numeric
Can you show me the coding needed fix this?
At this point you are trying to assign value which is of type string and the parameter is bound as string (nvarchar). You need to convert it at first.
' Let's suppose that this is a value from your textbox
Dim strNumber As String = "12"
' Prepare a placeholder to convert your string value into integer
Dim myInteger As Integer
' Try to convert
If Int32.TryParse(strNumber, myInteger) Then
'If the conversion is successful
Dim myConnection As New SqlConnection("Your ConnectionString")
Dim myCommand As New SqlCommand("INSERT INTO Foo(Bar) VALUES (#Bar", myConnection)
'Use this syntax to assign values to parameters
myCommand.Parameters.AddWithValue("Bar", myInteger)
End If
This snippet also uses AddWithValue method. I suggest you to use this approach.