无法将类型为“System.DBNull”的对象强制转换为“System.String”。错误

时间:2012-05-11 05:17:29

标签: c# sql arraylist

我一直收到此错误,因为该记录的VendorID为null。我已经看过这个问题已被问过几次了,看起来我应该检查是否在它转换之前是否为null并在dbtable中输入它,但我不知道该怎么做。< / p>

public static PartOrder findPartOrder(string orderNo)
    {
        PartOrder aPartOrder = new PartOrder();
        OleDbDataAdapter myAdapter = new OleDbDataAdapter();
        if (aConnection.State == ConnectionState.Closed)
            aConnection.Open();
        OleDbCommand cmd = aConnection.CreateCommand();
        OleDbDataReader dbReader = null;
        cmd.CommandText = "SELECT * FROM PartOrder WHERE OrderNo = '" + orderNo + "'";
        dbReader = cmd.ExecuteReader();

        while (dbReader.Read())
        {
            aPartOrder.OrderNo = (string)dbReader.GetValue(0);
            aPartOrder.Length = (string)dbReader.GetValue(1);
            aPartOrder.Finish = (string)dbReader.GetValue(2);
            aPartOrder.Cost = (string)dbReader.GetValue(3);
            aPartOrder.PartDrawingNo = (string)dbReader.GetValue(4);
            aPartOrder.VendorId = (string)dbReader.GetValue(5);
            aPartOrder.ShopId = (string)dbReader.GetValue(6);
            aPartOrder.Completed = (string)dbReader.GetValue(7);
        }

        dbReader.Close();
        return aPartOrder;
    }

再次,行“aPartOrder.VendorId =(string)dbReader.GetValue(5);”得到错误,因为VendorId为空。

4 个答案:

答案 0 :(得分:3)

对于这个特定的行尝试这个:

aPartOrder.VendorId = dbReader.GetValue(5)==DBNull?"":dbReader.GetValue(5).value;

更好的是编写辅助函数:

private static string MyToString(object o)
{
    if(o == DBNull.Value || o == null) 
       return "";

    return o.ToString();
}

并使用它:

aPartOrder.VendorId = MyToString(dbReader.GetValue(5));

答案 1 :(得分:1)

一行答案

aPartOrder.VendorId = dbReader.IsDBNull(5) ? "" :(string)dbReader.GetValue(5);

答案 2 :(得分:0)

使用OleDbDataReader.IsDBNull(ordinal)验证字段值。

if(!dbReader.IsDBNull(5))
  aPartOrder.VendorId = dbReader.GetString(5);

建议:始终使用参数/预编译的sql语句来防止SQL-Injection攻击。

cmd.CommandText = "SELECT * FROM PartOrder WHERE OrderNo = @OrderNo";
cmd.Parameters.Add("@OrderNo",System.Data.OleDb.OleDbType.VarChar,20).Value=orderNo;
dbReader = cmd.ExecuteReader();

答案 3 :(得分:0)

dbReader.GetValue(5).HasValue ? dbReader.GetValue(5).ToString() : String.Empty