[英]Specified Cast is not valid - C#
I'm trying to do an AppendLine
with this 我正在尝试与此做一个
AppendLine
reportLayout.AppendLine(
"Sold Items".PadRight(25) +
Convert.ToString(BatchCalculation.NoOfItems(dBCommand, transDate, reportType)));
And I'm getting an exception thrown 我正在抛出异常
Specified Cast is not valid
指定的演员表无效
my NoOfItems
is a static
method and it returns an int 我的
NoOfItems
是一个static
方法,它返回一个int
EDIT: Last lines of code in NoOfItems
method 编辑:
NoOfItems
方法中的最后一行代码
...
using (DbDataReader reader = dBCommand.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
//hsBatch.currentTC = (int)reader["CURRENTTC"];
//hsBatch.currentAmt = (decimal)reader["CURRENTPYMTAMT"];
//Cancellation fee
hsBatch.TotalNoOfitems = (int)reader["TOTALNOOFITEMS"];
}
}
}
}
}
finally
{
if (connection.State == ConnectionState.Open)
connection.Close();
}
return hsBatch.TotalNoOfitems;
}
数据库可以返回null,所以我建议检查DBNull
hsBatch.TotalNoOfitems = reader["TOTALNOOFITEMS"] != DBNull.Value ? int.Parse(reader["TOTALNOOFITEMS"].ToString()):0;
It seems you have a problem with type mapping ( RDBMS Number
is not necessary .Net int
): 似乎您有类型映射问题( RDBMS
Number
不是必需的.Net int
):
// (int) - cast like this may well be incorrect:
// reader["TOTALNOOFITEMS"] is not nesseary int or can be cast to int
hsBatch.TotalNoOfitems = (int)reader["TOTALNOOFITEMS"];
Instead of 代替
if (reader.HasRows)
{
while (reader.Read())
{
//hsBatch.currentTC = (int)reader["CURRENTTC"];
//hsBatch.currentAmt = (decimal)reader["CURRENTPYMTAMT"];
//Cancellation fee
hsBatch.TotalNoOfitems = (int)reader["TOTALNOOFITEMS"];
}
}
Put 放
// if: we don't want "while" since we read one record only
// reader.HasRows is redundant - if we manage to read a record we have it
if (reader.Read())
{
// hsBatch.currentTC = Convert.ToInt32(reader["CURRENTTC"]);
// hsBatch.currentAmt = Convert.ToDecimal(reader["CURRENTPYMTAMT"]);
// What ever RDBMS type mapping is (byte, short, int, long, decimal
// or even string - depending on query, RDBMS and settings)
// try convert it into int - Int32
hsBatch.TotalNoOfitems = Convert.ToInt32(reader["TOTALNOOFITEMS"]);
}
There's one more (possible) issue: if TOTALNOOFITEMS
field contains NULL
value. 还有一个(可能的)问题:如果
TOTALNOOFITEMS
字段包含NULL
值。 If it's your case, you can put 如果是您的情况,可以放
hsBatch.TotalNoOfitems = reader["TOTALNOOFITEMS"] == DBNull.Value
? 0 // or whatever value in case of null
: Convert.ToInt32(reader["TOTALNOOFITEMS"]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.