Saeid
Saeid

Reputation: 2036

Error "Specified cast is not valid" in query

I have a funny problem. I want to execute this query, but this error happen:

"Specified cast is not valid."

Can any body help me?

here is my code:

 string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlConnection sqlconn = new SqlConnection(connStr);
        SqlCommand sqlcmd = new SqlCommand();
        sqlcmd = new SqlCommand("SELECT max(ID) FROM AddNews ", sqlconn);

        sqlconn.Open();
        int ID = ((int)sqlcmd.ExecuteScalar());
        sqlconn.Close();

Upvotes: 1

Views: 4764

Answers (6)

Sagar Hirapara
Sagar Hirapara

Reputation: 1697

you have to change as follow


int ID=int.Parse(cmd.ExecuteScalar().ToString());

Upvotes: 1

Akrem
Akrem

Reputation: 4652

you can test if your value is an int first

int ID;
int.TryParse(sqlcmd.ExecuteScalar(), out ID);

Upvotes: 0

Arpit
Arpit

Reputation: 12797

sqlcmd.ExecuteScalar()); 

it returns an object not an int.

try this

Object s= cmd.ExecuteScalar()
int x=Integer.Parse(s.ToString))

Upvotes: 0

Srinivas
Srinivas

Reputation: 1063

Instead of ((int)value) use Convert.ToInt32(value). It will work.

Upvotes: 0

StarPinkER
StarPinkER

Reputation: 14271

The result is cast to an int at the SQL level. The returned value will be an int, or defaulted to 0 if null.

You can use Convert.ToInt32(sqlCmd.ExecuteScalar()) instead of (int) or (int?)sqlCmd.ExecuteScalar() ?? 0;

Upvotes: 1

Aristos
Aristos

Reputation: 66641

There is a case the you may not have results and the return can be null.

You better try

int? MaxID = sqlcmd.ExecuteScalar() as int?;

and check if the MaxID is not null.

Upvotes: 1

Related Questions