asp:TextBox上的动态ID?

时间:2012-02-20 14:12:57

标签: c# .net webforms

这是我的代码,位于.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”?

2 个答案:

答案 0 :(得分:5)

您需要为文本框创建一个容器,例如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);

        }

    }
}

答案 1 :(得分:4)

以下是Dynamically adding textbox control in ASP.Net的链接。希望它适合你。