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 a schoolboy syntax error.
objConn = new SqlConnection(strConnection); objConn.Open(); objCmd = new SqlCommand(strSQL, objConn); rsData = objCmd.ExecuteReader(); rsData.Read(); if (!(rsData["usr.ursrdaystime"].Equals(System.DBNull.Value))) { strLevel = rsData["usr.ursrdaystime"].ToString(); }
Would this allow me to check whether the SQL connection is returning just a value and if so then populating my string?
I'm used to being able to just check the below to see if a value is being returned and not sure I'm doing it correctly with C#
If Not IsDBNull(rsData("usr.ursrdaystime"))
Any help would be appreciated!
To evaluate database fields to determine whether their values are DBNull, you can pass the field value to the DBNull. Value. Equals method. However, this method is rarely used because there are a number of other ways to evaluate a database field for missing data.
The DBNull class represents a nonexistent value. In a database, for example, a column in a row of a table might not contain any data whatsoever. That is, the column is considered to not exist at all instead of merely not having a value. A DBNull object represents the nonexistent column.
Empty; Please do not confuse the notion of null in C# language with a DBNull object. In an object-oriented programming language, null means the absence of a reference to an object, whereas DBNull represents an uninitialized field or nonexistent database column.
Null is similar to zero pointer in C++. So it is a reference which not pointing to any value. DBNull. Value is completely different and is a constant which is returned when a field value contains NULL.
This should work.
if (rsData["usr.ursrdaystime"] != System.DBNull.Value)) { strLevel = rsData["usr.ursrdaystime"].ToString(); }
also need to add using statement, like bellow:
using (var objConn = new SqlConnection(strConnection)) { objConn.Open(); using (var objCmd = new SqlCommand(strSQL, objConn)) { using (var rsData = objCmd.ExecuteReader()) { while (rsData.Read()) { if (rsData["usr.ursrdaystime"] != System.DBNull.Value) { strLevel = rsData["usr.ursrdaystime"].ToString(); } } } } }
this'll automaticly dispose (close) resources outside of block { .. }.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With