先判断一下 dr.IsDBNull()
然后再取值

解决方案 »

  1.   

    if(dr.Read())
    {
    string aa=dr[0].ToString();
    }
      

  2.   

    IDataReader中所有的GetXXXX()函数,只有其在数据库中的字段类型跟所使用的函数类型相同时才发起作用,不然会发生 System.InvalidCastException: 指定的转换无效。
    比如,你数据库中的字段类型为INT,而你用GetString()来取,就会发生System.InvalidCastException的异常。
    当初,我看这个函数的提示信息“返回指定字段的字符串值”还以为无论数据库中字段是什么类型,返回的都是字符串类型呢。
    Mono中GetString()的实现:
    public override string GetString (int i)
    {
        object value = GetValue (i);
        if (!(value is string)) {
            if (value is DBNull) 
                throw new SqlNullValueException ();
            throw new InvalidCastException ("Type is " + value.GetType ().ToString ());
        }
        return (string) value;
    }public override object GetValue (int i)
    {
        if (i < 0 || i >= command.Tds.Columns.Count)
    throw new IndexOutOfRangeException ();    if ((command.CommandBehavior & CommandBehavior.SequentialAccess) != 0) {
    return ((Tds)command.Tds).GetSequentialColumnValue (i);
        }    return command.Tds.ColumnValues [i];
    }
      

  3.   

    if(!dr[0].IsDBNull())
    {
    .....
    }
      

  4.   

    最简单直接的就是:dr[0].ToString()