ASP.NET - 如何从 Repeater Control 中动态生成的下拉列表中获取选定值

ASP.NET - How to get selectedvalues from dynamicallyproduced dropdownlists inside Repeater Control

您好,ASP.NET 中有以下 vb 代码:

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SQL_SRC_DEV_HIERACHY">
    <ItemTemplate>
        <p class="input_title">Hierachy:
            <asp:Literal ID="Literal1" runat="server" Text='<%# Eval("Hierarchy_SKey")%>'></asp:Literal><br />
        </p>
        <asp:DropDownList ID="DropDownList_H" runat="server" DataSourceID="SQL_SRC_DEV_GROUPINGDESCS" DataTextField="Description" DataValueField="FTE_PARENT_SKEY"></asp:DropDownList><br />
    </ItemTemplate>
</asp:Repeater>

我现在需要为创建的每个下拉列表实例获取选定值,并将 += 赋给一个变量,以便我可以根据选定值构建 SQL INSERT 命令。

任何人都可以指出我实现这一目标的正确方向吗?谢谢。

您可以在代码隐藏中循环 Repeater 中的项目,并使用 FindControl 获取 DropDownList 的 SelectedValue。

protected void Button1_Click(object sender, EventArgs e)
{
    //loop all the items in the repeater
    foreach (RepeaterItem item in Repeater1.Items)
    {
        //use findcontrol to locate the dropdownlist and cast it back to one
        DropDownList drp = item.FindControl("DropDownList_H") as DropDownList;

        //display the result
        Label1.Text += drp.SelectedValue;
    }
}

感谢 VDWWD - 我已经转换为 VB 并且效果很好!非常感谢。

VB版本如下所示:

Protected Sub GEN_CODE()

    Dim txtField As DropDownList
    Dim DDL_Values As String = ""
    For Each item In Repeater1.Items

        //use findcontrol to locate the dropdownlist and cast it back to one
        txtField = item.FindControl("DropDownList_H")

        //display the result
        DDL_Values += " " + txtField.SelectedValue

    Next

End Sub