在GridView的RowBound事件上将SqlDataReader DataItem强制转换为DataRowView时出错

chr*_*rtt 3 c# asp.net ado.net gridview casting

我有一个GridView,我分配DataSource和Bind像这样:

protected void Search(object sender, EventArgs e)
{
    using(SqlConnection con = new SqlConnection(constring))
    using(SqlCommand com = new SqlCommand("XXX", con))
    {
        com.CommandType = CommandType.StoredProcedure;

        // parameter declarations are here

        con.Open();

        SqlDataReader rdr = com.ExecuteReader();
        gvResults.DataSource = rdr;
        gvResults.DataBind();

    }
}
Run Code Online (Sandbox Code Playgroud)

然后有一个OnRowBound方法,如下所示:

protected void gvResults_OnRowBound(object sender, GridViewRowEventArgs e)
{   
    GridViewRow row = e.Row;

    if (row.RowType != DataControlRowType.DataRow) return;

    DataRowView rowdata = (DataRowView)row.DataItem;

    // fancy stuff will happen here

}
Run Code Online (Sandbox Code Playgroud)

当到达尝试将行的DataItem强制转换为DataRowView的行时,将抛出一个错误,其中包含:

无法强制转换'System.Data.Common.DataRecordInternal'类型的对象来键入'System.Data.DataRowView'

我明白我显然没有将这个DataItem强制转换为正确的类,但我的问题是当DataSource是一个SqlDataReader时,什么是正确的类

或者我完全走错了轨道?

Mag*_*nus 7

正确的类型是 IDataRecord