Farmer
Farmer

Reputation: 10983

Create labels dynamicly on ASP.NET (VB)

I want to create labels in my page dynamicly, for example the user will choose in a textbox the number of labels, and I will display the number of this label with .text = "XYZ".

Thanks.

Upvotes: 1

Views: 4070

Answers (3)

Chad Levy
Chad Levy

Reputation: 10140

There's a number of things that will need to be done to make this work, but to simply dynamically create controls and add them to the page, you will need a Placeholder on your ASPX page:

<asp:TextBox ID="txtLabelCount" runat="server" />
<asp:Button ID="btnCreate" runat="server" Text="Create" /><br />
<asp:Placeholder ID="PlaceHolder1" runat="server" />

Then, in btnCreate's click event handler:

' Number of labels to create. txtLabelCount should be validated to ensure only integers are passed into it
Dim labelCount As Integer = txtLabelCount.Text

For i As Integer = 0 To labelCount - 1
    ' Create the label control and set its text attribute
    Dim Label1 As New Label
    Label1.Text = "XYZ"

    Dim Literal1 As New Literal
    Literal1.Text = "<br />"

    ' Add the control to the placeholder
    PlaceHolder1.Controls.Add(Label1)
    PlaceHolder1.Controls.Add(Literal1)
Next

Upvotes: 0

Damien Dennehy
Damien Dennehy

Reputation: 4064

The quick and dirty method (this example adds 10 labels and literals to a PlaceHolder on an ASP.NET page:

Dim c As Integer = 0
While c < 10
    Dim lab As New Label()
    Dim ltr As New Literal()
    lab.Text = c.ToString()
    ltr.Text = "<br/>"
    PlaceHolder1.Controls.Add(lab)
    PlaceHolder1.Controls.Add(ltr)
    C+=1
End While

Upvotes: 2

bechbd
bechbd

Reputation: 6341

Look at using a Repeater control:

Using the ASP.NET Repeater Control

Data Repeater Controls in ASP.NET

Upvotes: 0

Related Questions