【问题标题】:Unable to Use repeater item on Item bound function无法在项目绑定功能上使用中继器项目
【发布时间】:2019-03-27 05:39:36
【问题描述】:

我的代码在转发器 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;
    }}

【问题讨论】:

    标签: asp.net linq webforms


    【解决方案1】:

    与其使用匿名类型投影到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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 2020-09-05
      相关资源
      最近更新 更多