Question

I have a relatively simple ASP.NET problem (I should think) that regrettably I am unable to solve by myself. What I am trying to do is the following:

  1. On a page I load a number of controls (Text Boxes) programmatically;
  2. following this load the user should be able to select a value to load into the Textbox from a panel control that is added to the page following the click of a button
  3. Once the panel is closed, the selected text from the panel should be loaded into the textbox

However, in the vb.net statements below when run the "test" string never makes it to the textbox - any help with resolving this would be greatly appreciated.

Public Class test
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Controls_Load()
End Sub
Public Sub Controls_Load()
    Dim ttf_tb As New TextBox With {.ID = "ttf_tb"}
    Master_Panel.Controls.Add(ttf_tb)
    Dim ttf_button As New Button
    Master_Panel.Controls.Add(ttf_button)
    AddHandler ttf_button.Click, AddressOf TTF_BUTTON_CLICK
End Sub
Public Sub TTF_BUTTON_CLICK(sender As Object, e As EventArgs)
    Dim str As String = sender.id
    Dim panel As New Panel
    panel.ID = "TTF_Panel"
    panel.Width = 300
    panel.Height = 300
    Master_Panel.Controls.Add(panel)
    panel.BackColor = Drawing.Color.Black
    panel.Style.Add(HtmlTextWriterStyle.Position, "absolute")
    panel.Style.Add(HtmlTextWriterStyle.Left, "200px")
    panel.Style.Add(HtmlTextWriterStyle.Top, "100px")
    panel.Style.Add(HtmlTextWriterStyle.ZIndex, "100")
    Dim CL_Button As New Button
    CL_Button.ID = "TTF_Close_" & Replace(str, "TTF_Button_", "")
    panel.Controls.Add(CL_Button)
    AddHandler CL_Button.Click, AddressOf TTF_Close_Button_Click
End Sub
Public Sub TTF_Close_Button_Click(sender As Object, e As EventArgs)
    Dim ttf_tb As TextBox = Master_Panel.FindControl("ttf_tb")
    ttf_tb.Text = "Test"
    Dim panel As Panel = FindControl("TTF_Panel")
    Master_Panel.Controls.Remove(panel)
End Sub
End Class
Was it helpful?

Solution 2

You should create / recreate your dynamic controls in the Init event:

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
    Controls_Load()
End Sub

This should allow you to maintain their state across PostBacks.

For more information about this topic, see the MSDN article on the ASP.NET Page Life Cycle.

OTHER TIPS

I think you need to re-create your controls in the Page_Init method. It's been a while since I've done web forms but I think it's something like:

When a user clicks the button a post back is fired. This re-creates a new instance of your class, creates the controls on the page, assigns any form values then calls your Page_Load event.

The problem is you are creating your controls too late, so the forms values are never assigned correctly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top