.net请教!!!Unable to cast object of type 'System.Data.DataRow' to type ~~

来源:百度知道 编辑:UC知道 时间:2024/07/04 11:22:29
public Student GetById(string xh)
{
DataTable dt = DataSource.ExecuteQuery("SELECT * FROM Student where xh='"+xh+"'");
int total = dt.Rows.Count;
IList ret = new ArrayList(total);
for (int i = 0; i < total; i++)
{
ret.Add(dt.Rows[i]);
}
if (total > 0)
{
return (Student)(ret[0]);
}
return null;
}
上面是我写的一段程序,当执行到return (Student)(ret[0]); 进弹出错误" Unable to cast object of type 'System.Data.DataRow' to type 'XKXT.Login.Data.Student'" student是我写的一个类,对应数据库的里面的表student,return (Student)(ret[0]);改为return ret[0] as student;会没有错误,但是调用这个方法却到null,明明ret[0]有值,也返回的是null!!
高手指教!!!
那怎么转换啊???
@syrenq
具体是怎么做啊,我新建实例了也不行啊!
Student student=new Student()
student=re

ret[0]里面数据的类型是一个datarow 当然不能直接通过显示转换成你自己写的一个类的(即时你自己写的类的结构和DataRow的结构一样,建议你新建一个Student实例 然后对其进行赋值再返回就可以了

感觉还是你的数据有点问题,查查你的数据先。