当数据源为Linq时,访问ItemDataBound事件中的列
我使用以下代码设置数据源:
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事件访问其中一列(如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
您没有将数据行绑定到控件(您绑定了匿名类型),因此不应将DataItem强制转换为DataRow。
尝试将行的数据设为:
var dataItem = e.Item.DataItem; // For example get your CustomerID as you defined at your anonymous type : string customerId = dataItem.CustomerID;
终于找到了,就像下面那样简单:
long customerID = long.Parse(DataBinder.Eval(e.Item.DataItem, "CustomerID").ToString());
这种.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,这里是Wayback Machine的页面: 匿名类型和ItemDataBound事件(存档版本)