1110
1110

Reputation: 6829

How to set null data in DataTable to empty string

I populated datatable object with data from database, and I need to check if some of them are NULL and set it to empty string.
The problem is that some data are NULL in database but they are "0" in DataTable.
I have tried to set to "", String.EmptyString etc. nothing works.

foreach (DataRow row in ds.Tables[0].Rows)
{
    foreach (DataColumn c in ds.Tables[0].Columns)
    {
        object value = row[c];

        if (value == DBNull.Value)
        {
            try
            {
                row[c] = "";

Upvotes: 1

Views: 11652

Answers (1)

DiskJunky
DiskJunky

Reputation: 4971

try changing to;

foreach (DataRow row in ds.Tables[0].Rows)
{
    foreach (DataColumn c in ds.Tables[0].Columns)
    {
        if (row.IsNull(c))
        {
            try
            {
                row[c] = string.Empty;

The row.IsNull(c) check is more reliable than directly comparing to DBNull.Value as it can evaluate more than one thing as equivilent to NULL in the DB.

Upvotes: 2

Related Questions