简体   繁体   中英

How to add HTML elements Dynamically (ASP.NET)

I am creating LINKbuttons Dynamically:

Lnk1

Lnk2

..

I want to Dynamically but a text(Or any HTML Element) between them for example:

Lnk1
Seperator
Lnk2
Sepeperator

Here is my code:

 for (int i=0;i<10;i++)
            {
    form1.Controls.Add(lnks[i]);
    Response.Write("Seperator<br>");
}

But in output I get the following picture:

在此处输入图片说明

Please let me know how to add one text exactly after one linkButton.

Take a look at this approach. You're on the right track, but you need to think of the form itself. The form has a collection property called Controls. If you instantiate controls in your for loop, you can effectively add each control sequentially. First, create your LinkButton instance and assign it's properties. Then, create whatever sort of separator control you would like to use. I used an HtmlGenericControl in this example which allows us to assign a text property (of Separator). Notice I started my loop at 1 instead of zero to match your example ... hopefully this helps.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        for (int i = 1; i < 11; i++)
        {
            LinkButton linkButton = new LinkButton();
            linkButton.Text = "Lnk" + i;
            linkButton.Click += linkButton_Click;
            form1.Controls.Add(linkButton);

            HtmlGenericControl p = new HtmlGenericControl("p");
            p.InnerText = "Separator";
            form1.Controls.Add(p);
        }
    }

    void linkButton_Click(object sender, EventArgs e)
    {
        Response.Redirect("http://www.stackoverflow.com");
    }
}

Try using this as a ref. its working code in my past project.

for (int i = 0; i <= rows - 1; i++)
            {
                HyperLink MyLink = new HyperLink();

                //Set the Hyperlink Text and ID properties.
                MyLink.Text = "YOUR TEXT";
                MyLink.ID = "Link Id";
                // Add a spacer in the form of an HTML <br /> element.
                Panel1.Controls.Add(new LiteralControl("<br />"));
                Panel1.Controls.Add(MyLink);
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM