简体   繁体   中英

C# Compare SqlDataReader column value with 0

I have this bit of code:

// Do comparisons for highlighting
if (cellNum == reader.GetOrdinal("MTD Carryover"))
{
   tempCell.Width = 155;

   if (reader.GetInt32(reader.GetOrdinal("MTD Carryover")) < 0)
   {
       tempCell.Attributes.Add("class", tempCell.Attributes["class"] + " " + "RedBackground");
   }
   else
   {
       tempCell.Attributes.Add("class", tempCell.Attributes["class"] + " " + "GreenBackground");
   }

   // Test for yellow last, MTD Carrover - 10% but still less than 0
   if (reader.GetInt32(reader.GetOrdinal("MTD Carryover")) > (reader.GetInt32(reader.GetOrdinal("MTD 
       Carryover")) - (reader.GetInt32(reader.GetOrdinal("MTD Carryover")) * .1))
                                    && (reader.GetInt32(reader.GetOrdinal("MTD Carryover")) > 0))
   {  
       tempCell.Attributes.Add("class", tempCell.Attributes["class"] + " " + "YellowBackground");
   }
}

I want to compare a SqlDataReader column value to see if it is less than than 0. If it is, I want to make the background green, if not I want to make it red. If it is within 10% of 0 but not over 0 I want to make it yellow.

I thought this worked. However when I use a checkbox that reloads the page with a URL parameter I get the following error:

Data is Null. This method or property cannot be called on Null values. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlTypes.SqlNullValueException: Data is Null. This method or property cannot be called on Null values.

I've confirmed this is the issue by removing the code and using the checkbox and reloading the page that this particular bit of code and the 0 is my real issue. I use the same code on other columns to compare with other SqlDataReader values and that works. This is the only area where I need to compare to something outside of the SqlDataReader stream.

I'm not sure how to properly compare a value from a SqlDataReader stream with 0. I've tried creating an Int32 variable and setting it to 0 for the comparison but I get the same result.

// Used in the SqlDataReader compare below for column highlighting
Int32 compareMTDCarryover = 0;

I'm relatively new at C# and have been using StackOverflow extensively on my first full website. I cannot seem to find the answer to this question though. Any help is appreciated.

通过更多的检查,我实际上在 SQL 的 MTD Carryover 字段中有我没有意识到的空值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM