2

I thought this would be the proper code to replace a null but it gives me an error "The name 'subt2' does not exist in the current context"

var SQLSELECT2 = "SELECT SUM(Price) FROM ProductEntered WHERE TransID=@0";
var sub2 = db.QueryValue(SQLSELECT2, transaction_id);

if(sub2 == null){
    var subt2 = 0.00;
    }
else{
    var subt2 = sub2;
    }

and in the page I have @subt2 I decided to try to explain what I am doing to hopefully get a better response. I have a page that you can add products to. It makes an entry into the table with the TransID as a reference to this page. This page pulls the SUM from Price where rows have this TransID. The problem lies when there is not a product entered in the table with this TransID. I need it to output a 0.00 when there is not data to be displayed.

James
  • 83
  • 10

3 Answers3

1

took me forever but I found a few articles and put them together. This is the code:

var SQLSELECT2 = "SELECT SUM(Price) FROM ProductEntered WHERE TransID=@0";
var sub2 = db.QueryValue(SQLSELECT2, transaction_id);

if(String.IsNullOrEmpty(Convert.ToString(sub2)))
{
    sub2 = 0.00;
}
James
  • 83
  • 10
0

When you define a variable by using a var (or an int, double, string, etc) it only exists in within the braces {} where it is defined. So since you are defining it inside the braces, it's not available later in the page. Better would be:

var SQLSELECT2 = "SELECT SUM(Price) FROM ProductEntered WHERE TransID=@0";
var sub2 = db.QueryValue(SQLSELECT2, transaction_id);

var subt2 = 0;
if(sub2 == System.DBNull){
    subt2 = 0.00;
}
else
{
    subt2 = sub2;
}
Knox
  • 2,909
  • 11
  • 37
  • 65
  • with code you wrote ate the bottom it gives an error Cannot implicitly convert type 'System.DBNull' to 'double' if I replace double with var it does not give an error but it also does not display anything. The top code gives a similar error. – James Sep 10 '13 at 21:57
  • Wow - I personally believe that QueryValue has a bug in it, because it sometimes returns null, sometimes returns a value, and sometimes returns System.DBNull which bizarrely is not the same as null. I'm not sure how my own code works now. In any case, i have revised my code to reflect how QueryValue works on a SUM. – Knox Sep 11 '13 at 14:14
  • Sadly, you have to look at this post http://stackoverflow.com/questions/4488727/what-is-the-point-of-dbnull/4488758#4488758 for more information about System.DBNull – Knox Sep 11 '13 at 14:55
  • with your updated code it gives this error: 'System.DBNull' is a 'type', which is not valid in the given context – James Sep 11 '13 at 21:17
0

I would try to replace it as follows:

var sub2 = db.QueryValue(SQLSELECT2, transaction_id);

var result = sub2 == null ? 0 : sub2;
return result;
Andrey Gubal
  • 3,481
  • 2
  • 18
  • 21