Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic IDs on asp:TextBox?

Tags:

c#

.net

webforms

This is my code, on a .ascx page :

<% 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 myTextBox_<%=i %> is not a valid identificator. So, how can I put "Dynamic IDs"?

like image 731
markzzz Avatar asked Feb 20 '12 14:02

markzzz


2 Answers

You need to create a container for the textboxes, such as a Panel control, and then use the Page_Load in the code behind to loop through and add the text boxes 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);

        }

    }
}
like image 109
BG100 Avatar answered Sep 19 '22 00:09

BG100


Here is the link for Dynamically adding textbox control in ASP.Net. Hope it works for you.

like image 23
Ebad Masood Avatar answered Sep 18 '22 00:09

Ebad Masood