Using C# Code Convert To Zero If DBNULL

RAVI 896 Reputation points
2024-03-23T10:15:02.4533333+00:00

Hello

I get this error

wwww

how to convert zero in c# code behind

Thanks

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,256 questions
{count} votes

Accepted answer
  1. Lan Huang-MSFT 25,556 Reputation points Microsoft Vendor
    2024-03-26T05:22:10.5466667+00:00

    Hi @RAVI,

    I tested your code using test data and did not reproduce your issue.

    But you can try using the code below.

     object objCompute = new_tablez.Compute("sum(Value)", null);
     if (objCompute != DBNull.Value)
     {
         subtotal_Account = Convert.ToDouble(objCompute);
     }
     else
     {
         subtotal_Account = 0;
     }
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. AgaveJoe 26,131 Reputation points
    2024-03-23T11:33:15.8466667+00:00

    In my opinion, the easiest solution is adding CASE expression to the SQL script that returns the record set. If NULL is found then return a zero. This way you don't have to add complexity to the code behind.

    DECLARE @NullTest TABLE (MyColumn INT);
    INSERT INTO @NullTest(MyColumn)
    VALUES	(null),
    		(1),
    		(null),
    		(2)
    SELECT MyColumn
    FROM @NullTest
    SELECT	CASE WHEN MyColumn IS NULL 
    			THEN 0 
    			ELSE MyColumn 
    		END AS MyColumn
    FROM @NullTest
    

    If you really want to update the code behind then write an "if" condition that checks for DBNull. Keep in mind you asked this same question recently and the community provided source code that checks for DBNull. The logic must execute before the Sum function. You did not share how the result set is fetched but the syntax is very simple.

    if (myDataReader["columnName"] == System.DBNull.Value)
    {
        myvar = 0;
    }
    else 
    {   
       myvar = myDataReader["columnName"]
    }
    
    
    

    Or you could use the ternary conditional operator

    Again, I would update the SQL not the code behind.

    1 person found this answer helpful.
    0 comments No comments