Dynamic identifiers in asp: TextBox?

This is my code on the page .ascx:

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

but i get an myTextBox_<%=i %>invalid id. So how can I put "Dynamic Identifiers"?

+5
source share
2 answers

You need to create a container for text fields, for example, a Panel control, and then use Page_Load in your code to loop and add text fields to the panel.

Example:

<%@ 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>

Code behind:

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);

        }

    }
}
+5
source

Here is the link for dynamically adding text field management to ASP.Net . Hope this works for you.

+4
source

All Articles