Tuesday, March 20, 2012

problem with select and int statement

hey the following code doesnt worki it comes up with an error Specified cast is not valid. pointing at the exceutescalar

any ideas?

cheers

string maxquery = "Select Max(activity_order) from roomactivitylk where room_code = 'v1106'";

//int max = 0;
int max;

SqlCommand cmd15 = new SqlCommand();
cmd15.Connection = con;
cmd15.CommandText = maxquery;
max = (int)cmd15.ExecuteScalar();

++max;
max++;
max = max + 1;
tbtest1.Text = max.ToString();

I'm not shure, but AFAIK aggregate functions (like MAX()) usually requires GROUP BY clause.

Try modify line with error such way.

max = cmd15.ExecuteScalar();

And look what woul be max equal to in debugger.

Looks like your query returns result which simply can't be parsed to integer.

|||

Your query is OK. Run the query in SQL directly, make sure it return integer. If not integer, you need to set it as 0 value.

|||

Be sure to check to see what happens if it returns NULL as well. I don't believe your code would work if that were the case.

No comments:

Post a Comment