Efficiently handling DBNull in C#

Hello friends,

Let’s go through about DBNull today.

DBNull represents a nonexistent value returned from the database. 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.

Ex

if (! DBNull.Value.Equals(row[fieldName]))
return (string) row[fieldName] + ” “;
else
return String.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.

Below is one way to abstract the DBNull implementation and return null to middle/front end of the Data layer.

SqlDataReader r = …;

String firstName = getString(r[COL_Firstname]);

private static string getString(object o)

{

if (o == DBNull.Value) return null;

return (string) o;

}

Hope you found this post useful. Please share your comments below.

Remove Duplicates in Dataset Efficiently

Hello guys,

Do you remember the pain of removing duplicates in fetched dataset by looping, comparing etc.

it can be handled easily by using DataView.ToTable Method. The syntax is below.

DataView.ToTable(bool distinct, string[] columnNames)

distinct: If it’s true, the returned DataTable contains rows that have distinct values for all its columns specified in the second parameter. Default value is false.

columnNames: A string array that contains a list of the column names to be included in the returned table. The order of columns in returned table would be same as it’s appear in the array.

Ex1

DataTable temp = dt.DefaultView.ToTable(true, “Region”);

Ex2

DataTable temp = dt.DefaultView.ToTable(true, “Region”, “City”);

Hope you liked the post. Please share your comments.

Reference:

DataView.ToTable Method