moe
moe

Reputation: 5249

Specified cast is not valid using C#

I have a database that has an ID column and the ID column is a BIGINT type. I believe my issue has to do with the converting the ID column for the proper type in order the insert code to work. I have tried to convert it but could not get the right syntax.

Here is my code...

OleDbCommand cmd1 = new OleDbCommand("select ID, Name", con);
cmd1.Connection = con;
con.Open();
int result = (int)cmd1.ExecuteScalar();
sqlcmd.CommandText = "INSERT INTO MyTable(ID, Name) VALUES(@ID, @Name)";
sqlcmd.Parameters.Clear();
sqlcmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = result;

Upvotes: 0

Views: 215

Answers (2)

Karl Anderson
Karl Anderson

Reputation: 34846

BIGINT = 64-bit, so use either the C# long type or System.Int64.

Also, change this line:

sqlcmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = result;

To this:

sqlcmd.Parameters.Add("@ID", SqlDbType.BigInt).Value = result;

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460108

Use long:

long result = (long)cmd1.ExecuteScalar();    

Range: from –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Signed 64-bit integer System.Int64

Upvotes: 8

Related Questions