项目绑定功能上无法使用转发器项目

时间:2018-10-23 04:44:07

标签: asp.net linq webforms

我的代码在转发器itemDataBound上抛出异常

  

其他信息:无法转换类型的对象   '<> f__AnonymousType4`18 [System.String,System.Int64,System.String,System.String,System.String,System.String,System.Int32,System.Int32,System.Decimal,System.Int32,System.Decimal ,System.Decimal,System.Int32,System.Int32,System.Int32,System.Decimal,System.String,System.Boolean]'   键入“ System.Data.DataRowView”。

  public void GetUploadFIlesDetils_Level2() 
    {
       var result2 = from t in dt.AsEnumerable()
                          where t.Field<string>("PracticeName") == practiceName  && t.Field<string>("Provider") == Provider
                          select new
                          {  
                              PracticeName = t.Field<string>("PracticeName"),
                              FileId = t.Field<long>("UploadFIlesID"),
                              FileName = t.Field<string>("FileName")
    }

    rptlevel2.DataSource = result2;
        rptlevel2.DataBind();

    }

我的ItemDataBound函数是:

  protected void rptlevel2_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {

          if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    DataRowView drv = (DataRowView)e.Item.DataItem;
    }}

1 个答案:

答案 0 :(得分:0)

与其使用匿名类型来投影到DataRowView中,不如创建一个模型类,其所有属性都与投影属性具有相同的命名,而不是:

public class Practice
{
    public string PracticeName { get; set; }
    public long FileId { get; set; }
    public string FileName { get; set; }
}

然后修改查询以包含模型类:

var result2 = from t in dt.AsEnumerable()
              where t.Field<string>("PracticeName") == practiceName  && t.Field<string>("Provider") == Provider
              select new Practice // add the model class name here
              {  
                   PracticeName = t.Field<string>("PracticeName"),
                   FileId = t.Field<long>("UploadFIlesID"),
                   FileName = t.Field<string>("FileName")
              };

最后,使用如上所述的模型类名称从DataItem对象进行强制转换以获取相应的行实例:

Practice practice = (Practice)e.Item.DataItem;