开发者

asp.net dynamic linkButtons click event problem

I have asp.net page on which I have placeholder and a button. After the button is clicked I want several LinkButtons to appear on my placeholder, and I want specyfic handler to be connected to click_event of my LinkButtons.

Here is the code:

protected void Button_Click(object sender, EventArgs e)

{

 for(开发者_如何学Go...)
  {

  LinkButton l = new LinkButton();

  l.ID = "link" + i;

  l.Command += new CommandEventHandler(link_Command);

  PlaceHolder1.Controls.Add(l);

 }

} 

void link_Command(object sender, CommandEventArgs e)

        {
            PlaceHolder1.Controls.Clear();
            Label l = new Label();
            l.Text = e.CommandArgument.ToString();
            PlaceHolder1.Controls.Add(l);
        }

The LinkButtons will be visible but their event won't fire. How should I solve this? I need to generate LinkButtons inside the Button_Click event, because only then I will know how many buttons to create. Please Help.


Well one of first problem i faced in my early days of programming, reminds me of those days.... It because you are trying to create/inject asp control dynamically and ASP.Net uses something ControlState and ViewState to retrieve the state of every control you placed on your page after postbacks. In your case there is no ControlState/ViewState is defined for every LinkButton you create because you actually created them dynamically..

I think the easy way to solve this problem could be using some Data Control eg.Repeater/GridView they handle ViewState issues seamlessly.

And the other way is to explore and read about Control State(a little complex).

Reagards,


The problem is that you are adding the LinkButtons on the initial rendering of the page (when the user clicks the button), but when it posts back, they haven't been re-created, so there is nothing for the page to bind the click events to. You will need to create them again in the Page_Load method if it's a postback. So you will probably also need to store some of the information you used to determine how to create the LinkButtons in ViewState, so that you can re-create them in Page_Load. Once you do this, the controls will be available to the page to bind the events to, and your handler will get called.


When you click created link button, it will post back the page. In every post back you must re-create the linkbutton and re-bind its event handler.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜