1
votes

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();
6
check the return type of "sqlcmd.ExecuteScalar());" - Arpit
It is exactly an integer! - Reza

6 Answers

1
votes

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.

1
votes

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;

1
votes
you have to change as follow


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

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

0
votes
sqlcmd.ExecuteScalar()); 

it returns an object not an int.

try this

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

you can test if your value is an int first

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