使用sqldatareader时报错,无法将类型为“System.Int32”的对象强制转换为类型“System.String”

this.DropDownListClass.SelectedValue = (reader.IsDBNull(4))?"null" :reader.GetInt32(4).ToString();
                 
                //this.DropDownListClass.SelectedValue = reader["stu_classID"].ToString();//reader.GetString(4)为什么不行??????

通过下面注释的内容读取列值时报错:无法将类型为“System.Int32”的对象强制转换为类型“System.String”

数据库中classID这列定义为int类型,因此想要获取该列的值就必须通过reader.getInt32(4),然后再将其转换为string类型

通过reader.getXXX(int i)来回去某列的值时,xxx必须与数据库中的类型保持一致,否则就会爆出雷同于以上的错误

也可以用reader[int i]来读取获得对象后在进行类型转换

原文地址:https://www.cnblogs.com/NoteofEveryDay/p/2680425.html