如何在Repeater中设置DropDownList选择值?

时间:2009-02-17 09:09:40

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

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

我的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所有可能的值。

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

例如,假设我们的可能属性值为ABC
如果Repeater的数据库输出包含其中两个值AB,则Repeater会输出两个DropDownList,两个值均为availablebla第一个A作为选定值,第二个B作为选定值。

修改
似乎将OnItemDataBound="repeater_ItemDataBound"添加到Repeater并在其中选择适当的值并不是我的理由。这是因为我还需要将可能更改的值保存到数据库中。

ItemDataBound的{​​{1}}事件在Repeater上的OnClick事件之前触发,并在保存新选择之前将所选值更改为旧值

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

当前代码:

Button

在代码隐藏中,<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使用Bryan Parker建议的方法来选择正确的值。

2 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分:1)

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

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