【问题标题】:Changing WebControl ID Inside of a Repeater更改中继器内的 WebControl ID
【发布时间】:2009-05-20 18:26:10
【问题描述】:
<ItemTemplate>
    <asp:Label runat="server"><%#DataBinder.Eval(Container.DataItem, "Question")%></asp:Label>
    <asp:DropDownList runat="server" id="<%#DataBinder.Eval(Container.DataItem, "QuestionID")%>">>
        <asp:ListItem value="1" text="Yes" />
        <asp:ListItem value="0" text="No" />
    </asp:DropDownList>
<ItemTemplate>

这大致就是我想要做的。显然,实现是错误的,但我找不到任何关于在实践中如何处理的信息。任何帮助表示赞赏。

编辑:我想要做的是为这个中继器中的每个项目添加一个 DropDownList,并在提交表单后,使用每个是/否答案的 ID 输入数据库。我使用的 SqlDataReader 有两个字段:问题内容和问题 ID。

【问题讨论】:

  • 你不能像这样给控件一个动态ID。告诉我们您要做什么(为什么需要动态 ID?),我们可以回答。干杯

标签: asp.net web-controls


【解决方案1】:

我认为您最好在中继器中使用对 ID 的内置支持。如果目标是为其分配一个 ID,以便在绑定数据后轻松找到合适的控件,您可以尝试以下操作:

<asp:Repeater ID="Repeater1" runat="server>
    <ItemTemplate>
        <asp:Label ID="QuestionID" Visible="False" Runat="server"><%#DataBinder.Eval(Container.DataItem, "FieldContent")%></asp:Label>
        <asp:DropDownList ID="MyDropDownList" Runat="server"></asp:DropDownList>
    </ItemTemplate>
</asp:Repeater>

然后,在您的代码中,您可以遍历中继器中的项目,直到找到您要查找的标签:

foreach (RepeaterItem curItem in Repeater1.Items)
{
    // Due to the way a Repeater works, these two controls are linked together.  The questionID
    // label that is found is in the same RepeaterItem as the DropDownList (and any other controls
    // you might find using curRow.FindControl)
    var questionID = curRow.FindControl("QuestionID") as Label;
    var myDropDownList = curRow.FindControl("MyDropDownList") as DropDownList;
}   

Repeater 基本上由RepeaterItems 的集合组成。使用 ItemTemplate 标记指定 RepeaterItems。每个RepeaterItem 都有自己的一组控件,这些控件根据Repeater 的本质是相互关联的。

假设您正在从数据库中提取中继器数据。每个Repeater 项代表查询结果中单个行的数据。因此,如果您将 QuestionID 分配给标签并将 QuestionName 分配给 DropDownList,则标签中的 ID 将与下拉列表中的名称匹配。

【讨论】:

  • 我需要在加载表单时将 ID 设置为每条记录的 QuestionID,以便我可以在存储过程中使用这些 ID 和相应的值。
  • 这很简单。如果您为每个标签/文本框/等分配一个 ID 并将 QuestionID 添加为隐藏标签,则可以使用 RepeaterItem 的 FindControl 方法访问这些控件。
  • 好的,我现在必须阅读有关 FindControl 的更多信息。我试图了解如何将隐藏标签的 ID 与关联的 DropDownList 相关联。
  • 我已经编辑了我的答案,试图更好地回答你的问题。
【解决方案2】:

您能否从标记文件中删除控件,并挂钩中继器的 onItemDataBound 事件。在这种情况下,您应该能够“手动”创建下拉控件,分配您想要的任何 ID。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多