我想在asp.net中使用Repeater控件构建一个轮询系统,在DB中有2个表(Polls,PollItems)。并使用此代码进行选择民意调查:
var lstPoll = (from P in Conn.Polls.ToList()
orderby P.PollOrder
select new { P.Question, P.PollID, P.PollItems }).ToList();
RepeaterPoll.DataSource = lstPoll.ToList();
RepeaterPoll.DataBind();
PollItems表(P.PollItems)具有 PollItemID , PollAnswer 参数。
<asp:Repeater ID="RepeaterPoll" runat="server">
<ItemTemplate>
<%# Eval("Question")%>
<br />
<asp:RadioButtonList ID="rblItemPoll" runat="server" DataValueField='<%# Eval("PollItemID")%>' DataTextField='<%# Eval("PollAnswer")%>'></asp:RadioButtonList>
<br /><br />
</ItemTemplate>
</asp:Repeater>
但不是Eval PollAnswer和PollItemID到rblItemPoll。
请帮助我建立民意调查系统。
答案 0 :(得分:2)
试试这个:
1 - 使用Repeater
控件定义RadioButtonList
并指定OnItemDataBound
事件处理程序:
<asp:Repeater ID="RepeaterPoll" runat="server" OnItemDataBound="RepeaterPoll_OnItemDataBound">
<ItemTemplate>
<%# Eval("Question")%>
<br />
<asp:RadioButtonList ID="rblItemPoll" runat="server" />
<br /><br />
</ItemTemplate>
</asp:Repeater>
2-在RadioButtonList
事件上OnItemDataBound
实施DataBinding的逻辑:
protected void RepeaterPoll_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
dynamic item = e.Item.DataItem;
RadioButtonList list = (RadioButtonList)e.Item.FindControl("rblItemPoll");
list.DataValueField = "PollItemId";
list.DataTextField = "PollItemDescription";
list.DataSource = item.PollItems;
list.DataBind();
}
}
您可以直接在DataValueField
标签上定义DataTextField
和RadioButtonList
属性。
此外,我将DataItem
检索为dynamic
,因为您正在为LINQ查询结果创建匿名类型。