chrsmrrtt
chrsmrrtt

Reputation: 197

Error casting SqlDataReader DataItem to DataRowView on RowBound event of GridView

I have a GridView which I assign the DataSource and Bind like this:

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();

    }
}

There is then an OnRowBound method which looks like this:

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

}

When then line that attempts to cast the row's DataItem to DataRowView is reached an error is thrown which reads:

Unable to cast object of type 'System.Data.Common.DataRecordInternal' to type 'System.Data.DataRowView'

I understand that I'm obviously not casting this DataItem to the right kind of class, but my question is what is the right class to be casting to when the DataSource is a SqlDataReader?

Or am I on the wrong track completely?

Upvotes: 3

Views: 1679

Answers (1)

Magnus
Magnus

Reputation: 46919

The correct type would be IDataRecord

Upvotes: 7

Related Questions