我使用以下代码设置数据源:
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<string,bool,byte,string,string,string,long>
答案 0 :(得分:36)
终于找到它,就像下面这样简单:
long customerID = long.Parse(DataBinder.Eval(e.Item.DataItem, "CustomerID").ToString());
答案 1 :(得分:34)
这种.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的页面: Anonymous types and the ItemDataBound event (Archived version)
答案 2 :(得分:-2)
您没有将数据行绑定到您的控件(您正在绑定匿名类型),因此您不应将DataItem强制转换为DataRow。
尝试将行的数据设为:
var dataItem = e.Item.DataItem;
// For example get your CustomerID as you defined at your anonymous type :
string customerId = dataItem.CustomerID;