I\'m trying to execute a stored procedure and then use an if statement to check for null values and I\'m coming up short. I\'m a VB guy so please bear with me if I\'m making
I use String.IsNullorEmpty often. It will work her because when DBNull is set to .ToString it returns empty.
if(!(String.IsNullorEmpty(rsData["usr.ursrdaystime"].toString())){
strLevel = rsData["usr.ursrdaystime"].toString();
}
Ternary operator should do nicely here: condition ? first_expression : second_expression;
strLevel = !Convert.IsDBNull(rsData["usr.ursrdaystime"]) ? Convert.ToString(rsData["usr.ursrdaystime"]) : null
The idiomatic way is to say:
if(rsData["usr.ursrdaystime"] != DBNull.Value) {
strLevel = rsData["usr.ursrdaystime"].ToString();
}
This:
rsData = objCmd.ExecuteReader();
rsData.Read();
Makes it look like you're reading exactly one value. Use IDbCommand.ExecuteScalar
instead.
At first use ExecuteScalar
objConn = new SqlConnection(strConnection);
objConn.Open();
objCmd = new SqlCommand(strSQL, objConn);
object result = cmd.ExecuteScalar();
if(result == null)
strLevel = "";
else
strLevel = result.ToString();
Consider:
if(rsData.Read()) {
int index = rsData.GetOrdinal("columnName"); // I expect, just "ursrdaystime"
if(rsData.IsDBNull(index)) {
// is a null
} else {
// access the value via any of the rsData.Get*(index) methods
}
} else {
// no row returned
}
Also: you need more using
;p
if(!rsData.IsDBNull(rsData.GetOrdinal("usr.ursrdaystime")))
{
strLevel = rsData.GetString("usr.ursrdaystime");
}
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.isdbnull.aspx
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getordinal.aspx