There are a few things you do that are not needed and are likely to cause problems.
It:
- There is no need to store the management object in the session. The control itself should use ViewState and Session State to store information as necessary, and not the entire instance.
- You should not check PostBack when creating a control. It must be created every time to allow ViewState to work, and the event must be connected.
- Controls loaded after loading ViewState often have problems working correctly, so if possible, avoid loading while loading the page.
This code works for me:
Default.aspx
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="Test_User_Control._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"><title></title></head> <body> <form id="form1" runat="server"> <asp:PlaceHolder ID="PlaceHolder1" runat="server" /> </form> </body> </html>
Default.aspx.vb
Partial Public Class _Default Inherits System.Web.UI.Page Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init Dim control As Control = LoadControl("~/UserControl1.ascx") PlaceHolder1.Controls.Add(control) End Sub End Class
UserControl1.ascx
<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="UserControl1.ascx.vb" Inherits="Test_User_Control.UserControl1" %> <asp:Label ID="Label1" Text="Before Button Press" runat="server" /> <asp:Button ID="Button1" Text="Push me" runat="server" />
UserControl1.ascx.vb
Public Partial Class UserControl1 Inherits System.Web.UI.UserControl Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Label1.Text = "The button has been pressed!" End Sub End Class
Adrian clark
source share