How can I preempt the attempted assignment of DBNull to an int?

陌路散爱 提交于 2019-12-25 08:16:43

问题


The following code:

foreach (DataRow fillRateDataRow in dtFillRateResults.Rows)
{
    . . .
    var frbdbc = new FillRateByDistributorByCustomer
    {
        ShortName = fillRateDataRow["ShortName"].ToString(),
        Unit = fillRateDataRow["Unit"].ToString(),
        CustNumber = fillRateDataRow["Custno"].ToString(),
        MemberItemCode = fillRateDataRow["MemberItemCode"].ToString(),
        Qty = Convert.ToInt32(fillRateDataRow["Qty"]),
        QtyShipped = Convert.ToInt32(fillRateDataRow["QtyShipped"]),
        ShipVariance = fillRateDataRow["ShipVariance"].ToString(),
        CWeek = fillRateDataRow["CWeek"].ToString(),
        PAItemCode = fillRateDataRow["PAItemCode"].ToString(),
        PADescription = fillRateDataRow["PADescription"].ToString(),
        TransactionType = fillRateDataRow["TransactionType"].ToString(),
        SplitCase = fillRateDataRow["SplitCase"].ToString(),
        ReasonCode = fillRateDataRow["ReasonCode"].ToString(),
        ReasonDescription = fillRateDataRow["ReasonDescription"].ToString(),
        CompanyName = fillRateDataRow["CompanyName"].ToString()
    };

...fails once in a great while with, "Object cannot be cast from DBNull to other types. Exception Source: mscorlib Exception StackTrace: at System.DBNull.System.IConvertible.ToInt32(IFormatProvider provider) at System.Convert.ToInt32(Object value)"

So it seems that either Qty or QtyShipped are sometimes DBNull (the only int vals amidst a sea of strings).

Is there a way to say "if it's DBNull, assign 0 to the var" and thus avoid the exception?


回答1:


You can use a conditional expression:

QtyShipped = fillRateDataRow["QtyShipped"] != DBNull.Value ? Convert.ToInt32(fillRateDataRow["QtyShipped"]) : 0

If you need to do it a lot, making a helper method for this task would let you shrink your code for better readability.




回答2:


You can use this expression as well:

QtyShipped  = fillRateDataRow.Field<int?>("QtyShipped") ?? 0;


来源:https://stackoverflow.com/questions/40411518/how-can-i-preempt-the-attempted-assignment-of-dbnull-to-an-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!