简体   繁体   中英

How to pass DBNull when convert data type of item in DataTable: Object can't cast from DBNull to other types

I found almost case relate with SQL connection and SQLReader.

The problem is: when looping to all items in DataTable.

I must convert row r["Age"] and r["Numphone"] to double type.

Seem have any item null .

I tried for loop all rows to set field1 = "" .

    foreach (DataColumn dc in dt.Columns)
    {
        var field1 = r[dc].ToString();
        if (field1 == null)
            field1 = "";
    }

But my code not working.

foreach (DataRow r in dt.Rows)
{
    try
    {
        foreach (DataColumn dc in dt.Columns)
        {
            var field1 = r[dc].ToString();
            if (field1 == null)
                field1 = "";
        }

        double[] inforNum = { Convert.ToDouble(r["Age"]), Convert.ToDouble(r["Numphone"]) };
    }
    catch (Exception ex) { }
}

You are calling ToString() on it without check for null so it will fail, you should be checking for null first then call ToString() like:

foreach (DataColumn dc in dt.Columns)
{
    var field1 = r[dc]!=null ? r[dc].ToString() : "";
}

the same you need to do for the other line of code:

var age = r["Age"] !=null ? Convert.ToDouble(r["Age"]) : 0;
var numPhone = r["Numphone"] !=null ? Convert.ToDouble(r["Numphone"]) : 0;

double[] inforNum = new[]{ age , numPhone };

You can use DataRow.IsNull or even better DataRow.Field which supports nullable types:

foreach (DataRow row in dt.Rows)
{
    double? age = row.Field<double?>("Age");
    double? numphone = row.Field<double?>("Numphone");
    if(age.HasValue && numphone.HasValue)
    {
         double[] inforNum = { age.Value, numphone.Value };
    }
}

You should not use ToString to convert the double to a string first and then Convert.ToDouble to convert it back to a double. That's not efficient and could cause conversion issues. Instead simply cast it to the correct type which seems to be a double .

Also, don't use exceptions to control program flow and don't use empty cacth blocks.

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