解决GridView绑定时无法将类型为 <>f__AnonymousType0`2[xx] 的对象强制转换为类型“xxx”的方法

 当GridView 的数据源是匿名类型的对象时,在绑定事件里直接 (UserInfo)e.Row.DataItem 进行转换时,会报告如下的错误:

无法将类型为“<>f__AnonymousType0`2[System.String,System.Int32]”的对象强制转换为类型“UserInfo”。

此时,要在 RowDataBound 事件中得到数据源的数据,有下面的2种方法:

一是直接如果DataBinder类型得到,这种方法适合任何带属性名称的任何数据源,具体写法就是:
Response.Write("<li> Data = " + DataBinder.Eval(e.Row.DataItem, "Name"));

二是通过反射的方法得到数据,如下面的例子:

ASPX 代码
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--> <% @ Page Language = " C# " EnableViewState = " true " %>

<% @ Import Namespace = " System.Collections.Generic " %>
<% @ Import Namespace = " System.Linq " %>
<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>

< script runat ="server" >

  
// 测试的例子对象
  public class UserInfo
  {
    public String Name { set; get; }
    public
int id { set; get; }
  }

  protected
void Page_Load(object sender, EventArgs e)
  {
    List
< UserInfo > ul = new List < UserInfo > ();
    
for ( int i = 0 ; i < 10 ; i ++ )
    {
      UserInfo u
= new UserInfo();
      u.Name
= " 【孟子E章】 " + i.ToString();
      u.id
= i;
      ul.Add(u);
    }

    
if ( ! Page.IsPostBack)
    {      
      
var query = from u in ul
                  select
new
                  {
                    Name
= u.Name,
                    id
= u.id
                  };
      GridView1.DataSource
= query.ToList();
      GridView1.DataBind();
    }
  }

  protected
void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  {
    
if (e.Row.RowType == DataControlRowType.DataRow)
    {            
      Object o
= e.Row.DataItem;
      Type t
= o.GetType();
      System.Reflection.PropertyInfo name
= t.GetProperty( " Name " , typeof (System.String));
      System.Reflection.PropertyInfo id
= t.GetProperty( " id " , typeof (System.Int32));
      Response.Write(
" <li>id= " + id.GetValue(o, null ));
      Response.Write(
" name= " + name.GetValue(o, null ));    
    }
  }
</ script >

< html xmlns ="http://www.w3.org/1999/xhtml" >
< head runat ="server" >
  
< title ></ title >
</ head >
< body >
  
< form id ="form1" runat ="server" >
  
< asp:GridView ID ="GridView1" runat ="server" OnRowDataBound ="GridView1_RowDataBound" >
  
</ asp:GridView >
  
</ form >
</ body >
</ html >
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值