1

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] = "";
3
  • 1
    "The problem is that some data are NULL in database but they are "0" in DataTable." I don't believe you. :) Can you write a sample program to demonstrate this? I've NEVER seen this behavior before. Commented Feb 25, 2013 at 16:38
  • You need to first understand that the Database Schema if it allows nulls then setting to string.empty will work .if not then you need to set the null values to DBNUll and "" is not the same as setting to null Commented Feb 25, 2013 at 16:41
  • Believe me :) In int column is null and date column is null. I DataTable in Row.ItemArray[0]=0, Row.ItemArray[0]={1/1/1900 12:00:00 AM}. Commented Feb 25, 2013 at 16:56

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.