首页 > 解决方案 > 如何从代码隐藏 C# 中获取重复的 ID ASP 元素

问题描述

我的代码:

<asp:DataList ID="datalist" runat="server" >
    <ItemTemplate>
        <asp:Textbox ID="Values" runat="server" type="text" />
    </ItemTemplate>
</asp:DataList>
<asp:Button ID="Button1" runat="server" Text="SEND" OnClick="send" />

如何从 C# 后面的代码中获取 DataList 的每个 Values ID 元素?

标签: c#asp.net

解决方案


您循环 DataList 中的所有项目并使用 FindControl 来定位 TextBox。

protected void send(object sender, EventArgs e)
{
    //loop all the items in the datalist
    foreach (DataListItem item in datalist.Items)
    {
        //find the textbox with findcontrol
        TextBox tb = item.FindControl("Values") as TextBox;

        //do something with the textbox content
        string value = tb.Text;
    }
}

推荐阅读