How would I generate text fields for user input in ASP.NET C#?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,
I'm relatively new at this language, so I've been trying to find parallels
to problems I've run into in the past.

This is the hypothetical problem:
I want to write a CD inventory application. There is a page where it asks
the user for the number of tracks on a CD. After they enter the number of
tracks, I would like to generate that number of text fields on the page (i.e.
if user enters 30, I want to generate 30 text fields), so the user can enter
track titles.

I haven't found any ASP.NET books that talks about this yet, so I asked
around for ideas.

Here is what I heard:
1) Generate the entire form in Javascript and then submit the form. Let the
server-side now deal with it. (I don't like this idea too much, since I
don't want to assume that Javascript is working on the client.)

2) Create a <asp:table> in the aspx page with a column to have an
<asp:textbox> in it. In the code-behind, add new rows to that Table object

3) Try to create a textBox object and add it to Page.Controls collection.
(But I don't have control over the layout anymore.

When I tried to solve this problem in PHP, Coldfusion, or XSL, I could loop
the HTML textfield within a code block. However, this model does not
separate code from presentation any more. Are the above 3 suggestions the
best answers to this problem?

Are there any books or websites that might talk about such topics?

Thank you for your time.
 
Hi there,

Add this inside your aspx file:

<asp:TextBox ID="TextBox1" runat="server" /><br />
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="Button1_Click" /><br /><br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server" />

Add this method inside your code-behid file:

protected void Button1_Click(object sender, EventArgs e)
{
// Read the number of cd's
int numberOfCd = Convert.ToInt32(TextBox1.Text);

// Add textboxes for tracks
for (int i = 0; i < numberOfCd; i++)
{
// Create textbox
TextBox cdTrack = new TextBox();
cdTrack.ID = "track" + i.ToString();

// Create newline
LiteralControl newline = new LiteralControl();
newline.Text = "<br />";

// Add textbox
PlaceHolder1.Controls.Add(cdTrack);
PlaceHolder1.Controls.Add(newline);
}
}

Hope this helps,
Arjen
 
Hi Arjen,
I didn't know about the Placeholder class. I just read up on Placeholder's
class definition, and what you describe in the code is what I want to do.
And it's a lot cleaner and less complex.

Thank you! I'll go try this out.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top