Handle DBNull in C#

The shortest (IMHO) is: int stockvalue = (reader[“StockValue”] as int?) ?? 0; Explanation: If reader[“StockValue”] is of type int, the value will be returned, and the “??” operator will return the result If reader[“StockValue”] is NOT of type int (e.g. DBNull), null will be returned, and the “??” operator will return the value 0 (zero).

What is the point of DBNull?

I’m going to disagree with the trend here. I’ll go on record: I do not agree that DBNull serves any useful purpose; it adds unnecessary confusion, while contributing virtually no value. The argument is often put forward that null is an invalid reference, and that DBNull is a null object pattern; neither is true. For … Read more

DBNull if statement

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(); } } … Read more

handling dbnull data in vb.net

The only way that i know of is to test for it, you can do a combined if though to make it easy. If NOT IsDbNull(myItem(“sID”)) AndAlso myItem(“sID”) = sId Then ‘Do success ELSE ‘Failure End If I wrote in VB as that is what it looks like you need, even though you mixed languages. … Read more

What is the difference between null and System.DBNull.Value?

Well, null is not an instance of any type. Rather, it is an invalid reference. However, System.DbNull.Value, is a valid reference to an instance of System.DbNull (System.DbNull is a singleton and System.DbNull.Value gives you a reference to the single instance of that class) that represents nonexistent* values in the database. *We would normally say null, … Read more

Most efficient way to check for DBNull and then assign to a variable?

I must be missing something. Isn’t checking for DBNull exactly what the DataRow.IsNull method does? I’ve been using the following two extension methods: public static T? GetValue<T>(this DataRow row, string columnName) where T : struct { if (row.IsNull(columnName)) return null; return row[columnName] as T?; } public static string GetText(this DataRow row, string columnName) { if … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)