EverTheLearner
EverTheLearner

Reputation: 7200

Dynamically create a ASP.net Submit LinkButton using a Panel

I am trying to implement an application which will dynamically create a list with a button next to each item on that list. I am partially able to do this using the Panel control in the aspx page and adding html dynamically in the code behind. I am having problems adding the LinkButton dynamically which will do database work based on which ID it is. Is this even possible with what I have?:

aspx:

<asp:Panel ID="ItemPanel" runat="server">
</asp:Panel>

code behind:

...
StringBuilder sb = new StringBuilder();
string UserID;

while (dr.Read())
{
    UserID = Convert.ToInt32(dr["UserID"]);
    sb.Append("<div><b class='template'></b>");
    //Create LinkButton with event and code behind function
}

ItemPanel.Controls.Add(new LiteralControl(sb.ToString()));

Upvotes: 1

Views: 5437

Answers (1)

Cerebrus
Cerebrus

Reputation: 25775

You may want to take a look at this very recent question and if you have additional queries, then edit your question.

Edit (after OP's comment)


The purpose of posting that link was to give you an idea how to create the control dynamically. Since you ask, here's a simple bare-bones ASPX page that creates a LinkButton and attaches an eventhandler for the Click event. Not sure what you mean by "handle changes on the server", though.

<%@ Page Language="C#" %>

<script runat="server">

  protected void Page_Load(object sender, EventArgs e)
  {
    LinkButton lnk1 = new LinkButton();
    lnk1.Text = "Click me!";

    //lnk1.PostBackUrl = "SomeOtherPage.aspx";

    // Use the eventhandler to perform redirection, 
    // instead of the PostBackUrl to show it works.
    lnk1.Click += new EventHandler(lnk1_Click);

    // Add control to container:
    pnl1.Controls.Add(lnk1);
  }

  void lnk1_Click(object sender, EventArgs e)
  {
    Response.Redirect("SomeOtherPage.aspx");
  }

</script>

<html>
<head>
  <title>Untitled Page</title>
</head>
<body>
  <form id="form1" runat="server">
    <asp:Panel ID="pnl1" runat="server">
    </asp:Panel>
  </form>
</body>
</html>

Upvotes: 1

Related Questions