B. Clay Shannon B. Clay Shannon - 1 year ago 126
C# Question

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

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download