0
cmd = new OleDbCommand("SELECT max(substr(tr_refno,9,6))as REFID from ECHALLAN WHERE DEPT='" +tmpDept.ToString() + "' and substr(tr_refno,5,2) ='" + Tmpmonth + "'", con);                         
maxid = Convert.ToInt16( cmd.ExecuteScalar());

Error= InvalidCastException was unhandled by user code

4
  • 1
    your data types are invalid so be sure that whatever the data type for max(substr(tr_refno, 9, 6)) is matches the .NET type. also be sure to check that the value is coming back.... Commented Apr 22, 2014 at 10:32
  • 2
    Before Convert it. You could first check the nullity. Commented Apr 22, 2014 at 10:38
  • 1
    What is the result of the cmd.ExecuteScalar() looks like when you debug it? And please use parameterized queries. This kind of string concatenations are open for SQL Injection attacks. Commented Apr 22, 2014 at 10:44
  • Beware of SQL Injection! The way you just concatenate your parameter values to your query is a bar open to injections, which consists of a big security flaw. Use IDataParameter : msdn.microsoft.com/en-us/library/… Commented Apr 22, 2014 at 10:51

2 Answers 2

1

Before Converting it you could check the nullity:

var value = cmd.ExecuteScalar();
int maxI;
If(value !=null)
   maxId = Convert.ToInt32(value);
else 
//......................
Sign up to request clarification or add additional context in comments.

Comments

0

Try this command:

cmd = new OleDbCommand("SELECT Max(COALESCE(substr(tr_refno,9,6),0)) as REFID from ECHALLAN WHERE DEPT='" +tmpDept.ToString() + "' and substr(tr_refno,5,2) ='" + Tmpmonth + "'", con);      

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.