【问题标题】:How to set DropDownList's selected value inside a Repeater?如何在中继器内设置 DropDownList 选定值?
【发布时间】:2010-10-08 01:10:32
【问题描述】:

我需要创建一组DropDownLists 来显示和允许更改项目的属性组。

我的 ASP 页面上有以下代码。

<asp:Repeater runat="server" ID="repeaterProperties">
    <ItemTemplate>
        <p><asp:DropDownList runat="server" ID="ddProperty" OnInit="ddProperty_OnInit" /><p>
    </ItemTemplate>
</asp:Repeater>

ddProperty_OnInit 使用数据库查询的所有可能值填充DropDownList

如何根据Repeater的源数据设置每个创建的DropDownList的选择值?

例如,假设我们有ABC 的可能属性值。
如果Repeater 的数据库输出包含其中两个值AB,则Repeater 输出两个DropDownLists,这三个值都可用,第一个值选择A值和第二个以B 作为选定值。

编辑:
在我的情况下,似乎将OnItemDataBound="repeater_ItemDataBound" 添加到Repeater 并在其中选择适当的值并不是可行的方法。这是因为我还需要将可能更改的值保存到数据库中。

RepeaterItemDataBound 事件在 Button 上的 OnClick 事件之前触发,并在保存新选择之前将所选值更改为其旧值。

关于如何解决这个问题的任何建议?

当前代码:

<asp:Repeater runat="server" ID="repeaterJako" OnItemDataBound="repeater_ItemDataBound">
<ItemTemplate>
    <asp:DropDownList id="ddJako" runat="server" OnInit="ddJako_OnInit">
    </asp:DropDownList><br />
</ItemTemplate>
</asp:Repeater>
<asp:Button runat="server" id="updateButton" Text="Save" OnClick="update_OnClick" />

在代码隐藏中,ddJako_OnInit 使用所有可能的选项填充下拉列表,而repeater_ItemDataBound 使用 Bryan Parker 建议的方法来选择合适的值。

【问题讨论】:

    标签: c# asp.net data-binding drop-down-menu repeater


    【解决方案1】:

    也许我误解了你的问题......但这似乎正是 OnItemDataBound 的用途。 :)

    使用 FindControl 在事件处理程序中获取对 DropDownList 的引用。还要检查以确保该项目不是页眉/页脚。 MSDN 中的示例完成了这两件事:

    http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.onitemdatabound.aspx

    【讨论】:

    • 是的,这就是我想要的。阅读链接后,我要做的就是弄清楚将 DataItem 转换为什么。
    • @jwalkerjr 我做了,直到我发现它对我的情况没有帮助。好吧,我确实在一分钟前弄明白了,所以也可以。这是一个很好的答案,我只会添加它。
    【解决方案2】:

    关于我在编辑中指定的问题,DataBind 的时间起着重要作用。我曾经在Page_Init 事件中进行数据绑定,这导致repeater_ItemDataBound 事件在button_OnClick 事件之前被触发。

    解决方案是将数据绑定移至Page_PreRender 事件。
    DropDownList 的人口与所有选择仍在其 OnInit 事件中完成。

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 2011-11-18
      • 2015-06-14
      • 2011-01-18
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多