Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

More on dynamically-added controls

I have a page with a placeholder.  On page_init, I add a button "B" :

Private Sub addB()
  Dim b As New Button
  ph.Controls.Add(b)
  b.ID = "b"
  b.Text = "Button B"
  b.Visible = True
  b.EnableViewState = True
  AddHandler b.Click, AddressOf Me.b_Click
End Sub


b_Click then calls addC, which adds another button to the placeholder. 

Private Sub b_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
  Dim b As Button
  b = ph.FindControl("b")
  b.Text = "Clicked"
  addC()
End Sub


Private Sub addC()
  Dim c As New Button
  ph.Controls.Add(c)
  c.ID = "c"
  c.Text = "Button C"
  c.Visible = True
  c.EnableViewState = True
  AddHandler c.Click, AddressOf Me.c_Click
End Sub

Button C gets displayed, but when I click it, c_Click never gets called.

Can anyone explain why, or offer a solution?

Thanks.

Chris F
Wednesday, February 09, 2005

The second event is not getting fired because button "C" does not exist on the page when ViewState is loaded or when PostBack events are fired. A more detailed discussion can be found in Scott Mitchell's article from MSDN (link below).

It seems that you have the button "C"'s event handler hard coded on the page. Why not code the button onto the page and toggle it's Visible property instead of trying to dynamically add the control to the page?

http://msdn.microsoft.com/asp.net/default.aspx?pull=/library/en-us/dnaspp/html/dynamicui.asp

Brian Chiasson
Wednesday, February 09, 2005

Another possibility is to add a "ButtonAdded" flag to the ViewStateBag or the Session and check for that variable in the page's load cycle. If the variable exists and is true then call a method that recreates the button and adds it to the control structure.

Brian Chiasson
Wednesday, February 09, 2005

Well, this app is just to help me understand how the process works...I'm pretty new to .Net

I'm trying to build an app where there are a number of different steps for collecting data.  After each step, a different user control may added depending on the results of the previous step. 

I have some "generic" user controls for collecting the different types of data, but I'm having problems adding events for them to change the behavior of some of the buttons in some cases.

Chris F
Wednesday, February 09, 2005

I have found some use for placeholders but they can be a pain.

I do as suggested up the page, set up the different possible controls on the page, group them in <asp:panel 's and set them visible or not as necasery.

It seems crazy to me to add a control programmatically if you cannot add all the subs etc to do with that control programmatically too.

having the controls on the page means you escape programming a lot of postback/viewstate management stuff which is good too!

Aidan
Friday, February 11, 2005

*  Recent Topics

*  Fog Creek Home