How do I convert this VB.NET code to C#? [closed]
-
11-12-2019 - |
Question
Dim MaxItemID As Integer
Dim objCMD As New SqlCommand(StrSql, objConn)
MaxItemID = IIf(IsDBNull(objCMD.ExecuteScalar()), 0, objCMD.ExecuteScalar()) + 1
How do I do this in C#?
Solution
This should do it (and avoid executing the SQL twice):
var objCMD = new SqlCommand(StrSql, objConn);
var sqlRes = objCMD.ExecuteScalar();
int maxItemID = 1 + (Convert.IsDBNull(sqlRes) ? 0 : (int)sqlRes);
Note VB will convert the object
return of ExecuteScalar
to an int
implicitly, but C# will not.
OTHER TIPS
int MaxItemID = 0;
using(SqlCommand objCMD = new SqlCommand(StrSql, objConn))
{
MaxItemID = (Converter.IsDBNull(objCMD.ExecuteScalar()) ? 0 : objCMD.ExecuteScalar()) + 1;
}
int MaxItemID;
SqlCommand objCMD =new SqlCommand (StrSql, objConn);
MaxItemID = IsDBNull(objCMD.ExecuteScalar()? 0: objCMD.ExecuteScalar()) + 1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow