GridView排序事件的转换错误

时间:2014-01-15 23:02:28

标签: asp.net c#-3.0

我正在拦截RowDatabound事件并使用:

DbDataRecord record = (System.Data.Common.DbDataRecord)e.Row.DataItem;

访问未绑定的数据源列。它在页面加载和当我将过滤器应用于数据集时工作正常。但是,当我尝试在GridView列上启动排序时,我得到:

Error: Unable to cast object of type 'System.Data.DataRowView' to type 'System.Data.Common.DbDataRecord'

我想我已经将根问题追溯到排序中使用的绑定方法:

 SqlDataAdapter da = new SqlDataAdapter();        
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();        
    da.Fill(ds);

    if (eventArgs != null)
    {
        DataSet SortedData = new DataSet();
        ds.Tables[0].DefaultView.Sort = eventArgs.SortExpression + " " + GetSortDirection(eventArgs.SortExpression);
        SortedData.Tables.Add(ds.Tables[0].DefaultView.ToTable());
        GridView1.DataSource = SortedData;
    }
    else
    {
        GridView1.DataSource =  ds;
    }
    GridView1.DataBind();
}

我记得这是一个很难解决的问题,因为只有数据集才有排序属性

2 个答案:

答案 0 :(得分:0)

由于您将DataSet分配给GridView1.DataSource,因此e.Row.DataItem事件中RowDatabound的类型将为DataRowView而非{{1} }}。你需要改变这个:

System.Data.Common.DbDataRecord

到此:

DbDataRecord record = (System.Data.Common.DbDataRecord)e.Row.DataItem;

答案 1 :(得分:0)

我没有尝试对数据集进行排序,而是在使用SqlDataReader将其绑定到网格之前,将视图状态中的排序方向和列附加到查询。看起来我不顾一切地开始做一件简单的事......