Pregunta

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.

¿Fue útil?

Solución

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;
}

Otros consejos

I would try to replace it as follows:

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

var result = sub2 == null ? 0 : sub2;
return result;

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;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top