Meem Meem -4 years ago 121
C# Question

Specified cast is not valid in C#

I have a column which is of type bigint in the database table. I want it to retrieve and assign it to variable in C# as shown below in the example.

Example:

obj.Total1 = (Int32)reader["Slno"] != null ? (Int32)reader["Slno"] : 0;
obj.Total2 = (Int32)reader["Rlno"] != null ? (Int32)reader["Rlno"] : 0;


Note: Here
Slno
and
Rlno
are of type bigint in database table.

Error: Following is the error message.

Specified cast is not valid.

Answer Source

BigInt needs to be mapped to long which is the equivalent 64bit integer value in C#.

Also, you should alter your code to something like this:

int slnoCol = reader.GetOrdinal("Slno");
int rlnoCol = reader.GetOrdinal("Rlno");

obj.Total1 = !reader.IsDBNull(slnoCol) ? reader.GetInt64(slnoCol) : (long)0;
obj.Total2 = !reader.IsDBNull(rlnoCol) ? reader.GetInt64(rlnoCol) : (long)0;

EDIT:

After noticing your comment that Total1 and Total2 are int, you also need to change them to long

public long Total1 { get; set; }
public long Total2 { get; set; }

This is because int is a 32bit integer which cannot store the same max value as a 64bit integer which is what you are using in your table.

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