C# 当数据源为Linq时,访问ItemDataBound事件中的列
Im使用以下代码设置数据源:C# 当数据源为Linq时,访问ItemDataBound事件中的列,c#,asp.net,linq,C#,Asp.net,Linq,Im使用以下代码设置数据源: 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.CustomerPort
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>
f_uu匿名类型8
您没有将datarow绑定到控件(您绑定的是匿名类型),因此不应将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());
这种.NET4.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;
}
}
全部归功于:
由于页面现在显示错误404,以下是回程机器的页面:
所以我在这场比赛中迟到了两年,但没有人注意到这不会编译?“var”仍然试图在设计时推断数据类型,因为它是匿名类型,所以不能这样做。此代码应在第二行显示错误“无法解析符号'CustomerID'。假设.NET 4.0,RobD的方法是正确的。未找到