这是我的代码,在.ascx页面上:

<% for (int i = 1; i <= 10; i++)
   { %>
    <asp:TextBox ID="myTextBox_<%=i %>" runat="server" Width="100%" CssClass="focus_out reset_content"></asp:TextBox>
<% } %>

但是我知道myTextBox_<%=i %>不是有效的标识符。那么,如何放置“动态ID”?

最佳答案

您需要为文本框创建一个容器,例如Panel控件,然后使用后面代码中的Page_Load来遍历并将文本框添加到面板中。

例子:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Panel ID="pnlContainer" runat="server" />
    </div>
    </form>
</body>
</html>

后面的代码:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        for (int i = 1; i <= 10; i++) {

            TextBox txtNewTextBox = new TextBox();
            txtNewTextBox.ID = "myTextBox_" + i;
            pnlContainer.Controls.Add(txtNewTextBox);

        }

    }
}

10-04 14:41