How to Retrieve a Numeric Type from a SqlServer table?

F

Frank

Hello,

I am attempting to retrieve a numeric type froma a table.

I get an invalid cast exception when I use the following code in my data
layer:

//The problem definitley occurs in the line"id = (int)
cmdSelect.ExecuteScalar();"

public int GetId(string handle)

{

string strSelect = null;

SqlCommand cmdSelect;

int id = 0;


strSelect = "Select [ID] FROM members WHERE handle = @handle";

SqlConnection conDb = new SqlConnection( _connStr );

cmdSelect = new SqlCommand(strSelect, conDb);

cmdSelect.Parameters.Add("@handle", handle);

conDb.Open();

id = (int) cmdSelect.ExecuteScalar();

conDb.Close();

return id;

}



So how does one normally extract a numeric type? Do I have to cast it as a
decimal or double?



Thanks in advance.

Frank
 
N

Nicholas Paldino [.NET/C# MVP]

Frank,

Yes, this is the case. You will have to convert it manually, either
casting to a double, and then cast that to int (for which a cast applies).

Hope this helps.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

Frank said:
Hello,

I am attempting to retrieve a numeric type froma a table.

I get an invalid cast exception when I use the following code in my data
layer:

//The problem definitley occurs in the line"id = (int)
cmdSelect.ExecuteScalar();"

The problem here is taht you have no idea what ExecuteScalar will return,
it's possible that the return type is not castable to int, I would use
Convert.ToInt32 instead.
and even this is not 100% sure as you can get an overflow depending of the
value received.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top