Reputation: 2036
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
Reputation: 1697
you have to change as follow
int ID=int.Parse(cmd.ExecuteScalar().ToString());
Upvotes: 1
Reputation: 4652
you can test if your value is an int first
int ID;
int.TryParse(sqlcmd.ExecuteScalar(), out ID);
Upvotes: 0
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
Reputation: 1063
Instead of ((int)value)
use Convert.ToInt32(value)
. It will work.
Upvotes: 0
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
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