Lord Relix Lord Relix - 2 years ago 98
Vb.net Question

Specified cast is not valid when reading a Float column

Well I am stuck... again. Everything was sailing smooth until now. I am reading some data from the DB (something usual) but its giving me the specified cast is not valid error. Its not the first time I've dealt with this error; earlier on I had it with a date column. Anyway, I have a table that I need to read. Its data type is FLOAT. so this is the code I am using:

Dim rdr = sqlCmd.ExecuteReader
While rdr.Read
theResults.Add(New UserData With {
.BalAvailable = rdr.GetFloat(0),
.branch = rdr.GetInt32(1)
End While

This is running under a function; this is the Class...

Class UserData
Dim theResults = New List(Of UserData)

Property Branch As Integer
Property BalAvailable As Single

End Class

And this is the input part...

Dim clientNo As Integer = 0
Dim myResults = GetData(clientNo)
If Integer.TryParse(txtInput.Text, clientNo) Then
If myResults.Count = 1 Then
txtBalAvail.Text = CInt(myResults(0).BalAvail)

Everytime I input a value it gives me the specified cast is not valid error.

System.Data.SqlClient.SqlBuffer.get_Int32() +5270501
System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i) +62

I believe this could be related to the statements I use?

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

I am stuck. I also tried changing the rdr.GetFloat to Double, and in Integer.TryParse to Double.TryParse. I am so stuck!

Answer Source

The strongly-typed Get... methods (GetFloat, GetInt32, etc.) will only work if the data-type of the field is an exact match.

Use the GetFieldType method to examine the real data-type of the field, and either use the appropriate strongly-typed Get... method, or the untyped GetValue method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download