代码之家  ›  专栏  ›  技术社区  ›  Fabian

当数据源为Linq时访问itemDataBound事件中的列

  •  16
  • Fabian  · 技术社区  · 15 年前

    正在使用以下代码设置数据源:

        protected void Page_Load(object sender, EventArgs e)
        {
            var vacancies = from v in db.Vacancies
                        join c in db.Customers on v.CustomerID equals c.CustomerID
                        join cp in db.CustomerPortals on c.CustomerID equals cp.CustomerID
                        where cp.PortalID == Master.Portal.ID
                        select new
                        {
                            Title = v.Title,
                            Internship = (v.ContractID == 6),
                            Hours = v.Hours,
                            City = v.Customer.City.Name,
                            Degree = v.Degree.Title,
                            Contract = v.Contract.Title,
                            CustomerID = v.CustomerID
                        };
            rVacancies.ItemDataBound += new RepeaterItemEventHandler(rVacancies_ItemDataBound);
            rVacancies.DataSource = vacancies;
            rVacancies.DataBind();
        }
    

    现在我想知道如何从itemdatabound事件访问1列(如customerid)。

        void rVacancies_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
             // This doesnt seem to work, row would be null even though e.Item.DataItem has a value.
             DataRow row = (DataRow)e.Item.DataItem;
        }
    

    我发现e.item.dataitem包含我查询中的所有字段,e.item.dataitem的类型为

    f__AnonymousType8<string,bool,byte,string,string,string,long>
    
    3 回复  |  直到 7 年前
        1
  •  -2
  •   Canavar    15 年前

    您没有将数据行绑定到控件(您正在绑定匿名类型),因此不应将数据项强制转换为数据行。

    尝试将行的数据获取为:

    var dataItem = e.Item.DataItem;
    // For example get your CustomerID as you defined at your anonymous type :
    string customerId = dataItem.CustomerID;
    
        2
  •  36
  •   Fabian    15 年前

    最后找到它,简单如下:

    long customerID = long.Parse(DataBinder.Eval(e.Item.DataItem, "CustomerID").ToString());
    
        3
  •  34
  •   bleuthoot RobD    7 年前

    这种.NET 4.0方法确实也非常酷!

    public void PersonDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            dynamic person = e.Item.DataItem as dynamic;
    
            string name = person.Name;
            int age = person.Age;
        }
    }
    

    所有荣誉: http://www.kristofclaes.be/blog/2010/08/12/anonymous-types-and-the-itemdatabound-event/

    因为页面现在显示错误404,这里是来自回程机器的页面: Anonymous types and the ItemDataBound event (Archived version)