Adding Controls to DIV

Jarosław Błaszczyk 21 Reputation points
2022-02-02T19:32:55.427+00:00

I am beginner in programing. I would like to add dinamically Label (control) to div (col-2). In *.aspx I have:

<div class="article">
...
<div class="col-2">
...
</div>
</div>

and in *.aspx.vb I have:

Dim LT11 As New Label
...
LT11.Text = "Hello World"
Controls.Add(LT11)

But Label LT11 appears at the end of Webpage not inside <div class="col-2">

Have you got any idea how to place it inside DIV

Developer technologies VB
Developer technologies ASP.NET Other
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 60,161 Reputation points
    2022-02-02T20:06:04.807+00:00

    You have a misunderstanding of how Web Forms works here. Web Forms is a server-side framework for rendering HTML. In order for you to do anything on the server side programmatically Web Forms has to know about it. Web Forms doesn't actually do anything with the HTML inside the ASPX file other than compile the code blocks (if any) that you defined and add to the assembly it builds. The HTML itself is just passed along to the browser. In your ASPX code you're working with regular fields of .NET classes (web controls) only for those controls that you identified as being needed on the server side.

    There are 2 solutions here depending upon how you want to go. Since you're new to this I assume you want to stick with server side. Therefore you need to change the div that you want to use as the parent into a server side control. This will cause a field to be generated to back that field and then you can access it programmatically. To do that you can add the runat="server" attribute to the div in the HTML. Then on the ASPX side you would need to use a generic web control associated with the same id as the DIV. Finally you would add the new label to the Controls property of the server-side DIV.

    Alternatively instead of using an HTML DIV replace it with an <asp:Panel> element instead. If you drag and drop this from the Toolbox onto your form and then move it into the correct position within your HTML then the designer will auto-create the field that you can use instead. Now you can do as before and add the control to the panel's Controls property.

    <asp:Panel ID="somePanel" runat="server">
       <!-- Put label in here -->
    </asp:Panel>
    
    
    
    Dim LT11 As New Label
    ...
    LT11.Text = "Hello World"
    somePanel.Controls.Add(LT11)
    

    The other solution is to do this on the client using Javascript. This is actually the better route if you already have a client library you're using but since you're new to this I'll assume this is not the case yet.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.