Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, how to generate new html Div during foreach loop?

Tags:

c#

asp.net

Depend of number of results I got like 3 results and I want to assign each result to label text and put to new Div each new line. How I do that?

Collection<PSObject> output = pipeline.Invoke(); is where I stored results.

Here a sample C# codes,

foreach(PSObject psObject in output)
        {
            Label ipLabel = new Label();
            ipLabel.Text = psObject + "\r\n";
            div1.Controls.Add(ipLabel);
        }

Here a asp.net codes,

<div id="div1" runat="server"></div>

I got the right Label results but it all displayed in 1 div line instead of every div new line .

like image 404
StudentIT Avatar asked Nov 20 '13 19:11

StudentIT


2 Answers

Ideally, markup manipulation should be done using data-binding within your .aspx file rather than in your codebehind, but anyway:

foreach(PSObject psObject in output) {
    HtmlGenericControl div = new HtmlGenericControl("div");
    div.Controls.Add( new Label() { Text = psObject + "\r\n"; } );
    div1.Controls.Add( div );
}

This is how I would do it in the aspx file:

<div id="div1">
<% foreach(PSObject psObject in output) { %>
    <div>
    <%: psObject %>
    </div>
<% } //foreach %>
</div>

Note the use of <%: foo %> which is equivalent to <%= Server.HtmlEncode( foo ) %>.

like image 77
Dai Avatar answered Oct 26 '22 23:10

Dai


The "Panel" control outputs a div, so maybe you'd like to wrap the Label there:

foreach(PSObject psObject in output)
{
    Panel ipPanel = new Panel();
    Label ipLabel = new Label();
    ipLabel.Text = psObject;
    ipPanel.Controls.Add(ipLabel);
    div1.Controls.Add(ipPanel);
}

You could also put a "
" (newline for HTML, roughly) inside the label:

foreach(PSObject psObject in output)
{
    Label ipLabel = new Label();
    ipLabel.Text = psObject + "<br/>";
    div1.Controls.Add(ipLabel);
}
like image 43
McGarnagle Avatar answered Oct 27 '22 01:10

McGarnagle