无法将类型为“DynamicClass1”的对象强制转换为类型“ET_LINQ.ET_COURSE_MSTR”

今天看了书上的GridView事件的RowDataBound.然后自己写照着做起来了.

后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Asp_Net_Study_DataSourceBind : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //this.LinqDataSource1.Select = "new(OrderID,ShipAddress,CustomerID,CustomerID,OrderDate,ShipName)";
        this.GridView1.RowDataBound += new GridViewRowEventHandler(GridView1_RowDataBound);
    }

    void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.DataItem != null)
        {
            System.Data.DataRowView drv = (System.Data.DataRowView)e.Row.DataItem;
            if (Convert.ToDecimal(drv["Average_UnitPrice"]) > 24)
            {
                e.Row.BackColor = System.Drawing.Color.Brown;
                e.Row.ForeColor = System.Drawing.Color.White;
            }
        }
    }
}
前台GridView代码:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            DataSourceID="LinqDataSource1">
            <Columns>
                <asp:BoundField DataField="Average_UnitPrice" HeaderText="Average_UnitPrice" 
                    ReadOnly="True" SortExpression="Average_UnitPrice" />
                <asp:TemplateField>
                <ItemTemplate>
                <%# Eval("Categories.CategoryName")%>
                </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
<%--                <ItemTemplate>
                <asp:BulletedList DataSource='<%#Eval("Products")%>'
                 DataTextField="ProductName" runat="server" ID="BulletedList"/>
                </ItemTemplate>--%>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:LinqDataSource ID="LinqDataSource1" runat="server"
        ContextTypeName="DataClassesDataContext" EntityTypeName="" TableName="Products"
         GroupBy="Categories" 
            
            Select="new (key as Categories, it as Products, Average(UnitPrice) as Average_UnitPrice)">
        </asp:LinqDataSource>
我就奇怪怎了报错了.而且第一次看见这种错误.

不过看名字知道是因为字段是动态生成不能转换未DataRowView类型.

刚开始知道问题了.就去看看e.Row.DataItem究竟是什么类型.想就这样转换那种类型可以了..

没想到的是不能这样转换了..

在网上找了下相关的..终于找到解决方法:

void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var val = (Decimal)DataBinder.Eval(e.Row.DataItem, "Average_UnitPrice");

            if (val > 24)
            {
                e.Row.BackColor = System.Drawing.Color.Brown;
                e.Row.ForeColor = System.Drawing.Color.White;
            }
        }
    }

关键就在这里-->(Decimal)DataBinder.Eval(e.Row.DataItem, "Average_UnitPrice");

 

posted @ 2010-11-25 23:05  dancky  阅读(1942)  评论(0)    收藏  举报