开发者

Event of dynamically created Control not firing

I'm having a problem with a Web Control that is dynamically created and inserted in my page. I create a couple of LinkButtons, depending on the data of the search that was made, and开发者_运维问答 I'm trying to add an Event Handler to each of the Buttons, so it would filter the result.

The controls are initialized properly, but the event is never fired.

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
  Controls.Clear()

  Dim btn As Controls.LocalizableLinkButton
  For Each element As Generic.KeyValuePair(Of String, ResultFilterData) In m_list

    btn = New LocalizableLinkButton
    btn.ID = m_Name & "$lnk" & count
    btn.Label = element.Value.Label.Append(" (" + CStr(element.Value.Count) + ")")
    btn.CommandArgument = element.Value.Key
    AddHandler btn.Click, AddressOf Me.btn_Click

    Controls.Add(btn)
  Next
End Sub

Since this code is in Page_Init all the controls should be recreated on a postback. (The LocalizableLinkButton is just an extension of a LinkButton to add multilingual features to the text).

The problem is that the method btn_Click is never called. The Link Buttons are properly initialized on the callback, with the same ID's as before. But the event doesn't fire.

I'm using ASP.Net 2.0

Any ideas?


I finally figured out the problem ASP.NET had with my Link Buttons.

The error was in using a '$' sign in my ID for each LinkButton. ASP.NET apparently uses the $ sign to build the control hierarchy when it creates the Postback Javascript. Therefore it thinks that the LinkButtons are nested within a control that does not exist. And so the events aren't fired of course.

Once I removed the $ signs it worked properly.


You probably want to put this piece of code in the Page_Load and see. It's generally advised not to access controls in this Page_Init as there is no guarantee of the controls been created at this stage.

I'm no VB guy but i put this into the codebehind of the default.aspx and it works fine.

  protected void Page_Load(object sender, EventArgs e)
        {
            Button button = new Button();
            button.Click += new EventHandler(button_Click);
            button.Text = "test";
            Form.Controls.Add(button);
        }

        void button_Click(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜