2

I am trying to avoid database null values with 0 and if it is not null then get the original values.

but I am having some issues .

Here is my Sample Code:

    int Value = 0;
    for(int i = 0; i < tblValue.Rows.Count; i++)
    {
      if (tblValue.Rows[i][""]== DBNull.Value)//Here it always returns true.. even there are values at Position 1 and 
      {
         Value += 0;                        
      }
      else
      {
         Value += Convert.ToInt32(tblValue.Rows[i][""]);
      }

   }

Any Idea?

Am I checking DBNUll Value the wrong way?

Keren Caelen
  • 1,466
  • 3
  • 17
  • 38
John Sheedy
  • 287
  • 1
  • 8
  • 26
  • 6
    Why are you checking a column with an empty name? That looks wrong to me. (And why do you bother with `Value += 0` at all?) – Jon Skeet Jul 09 '13 at 12:38
  • 2
    You're indexing an empty column "". Sure you want to do this? What is your database query, or what columns does it return? By the way, check if you don't want to make this sum in the database it self with a `SELECT SUM(COLUMNNAME) FROM XXX`. The sum will be more efficient this way – saamorim Jul 09 '13 at 12:38
  • this is just a sample code. i have Column Name in my Actual code. – John Sheedy Jul 09 '13 at 12:42
  • 1
    Isn't it supposed to be `if (tblValue.Rows[i][column] is DBNull) {...}`? That's how I've always done it at least. – Alxandr Jul 09 '13 at 13:16
  • Are you sure that your table is not empty? – Edper Jul 09 '13 at 13:57

2 Answers2

1

Yes. Try (DBNull.Value.Equals(tblValue.Rows[i][""]);

http://msdn.microsoft.com/en-us/library/system.dbnull.value.aspx

jgriffin
  • 176
  • 1
  • 11
  • Thanks,, but it didn't work. i got the same result. its returned me Null value on position 1 Where i know that db value is not null.. :( – John Sheedy Jul 09 '13 at 12:47
  • 1
    So, if this is not working, and you are trying to replace the values for nulls, try it in the SQL statement instead: instead of: 'Select LLAMA from MOOSE' do: 'Select COALESCE(LLAMA,0) from MOOSE' If LLAMA is null, this will replace it with 0. – jgriffin Jul 10 '13 at 13:11
1

Try this:

int Value = 0;
for(int i = 0; i < tblValue.Rows.Count; i++)
{
    if (!IsDBNull(tblValue.Rows[i][""])) 
    {
        Value += Convert.ToInt32(tblValue.Rows[i][""]);
    }
}

This only increments the Value variable if the database value is NOT NULL.

Karl Anderson
  • 34,606
  • 12
  • 65
  • 80
  • @Alxandr - [MSDN Documentation for C# Convert.IsDBNull Method](http://msdn.microsoft.com/en-us/library/system.convert.isdbnull.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1) – Karl Anderson Jul 09 '13 at 13:20
  • Yes, that's fine and all, but it still means your code is invalid (as in, it won't compile), no? – Alxandr Jul 10 '13 at 06:43