动态创建的用户控件无法处理PostBack上的事件

6 asp.net user-controls postback dynamic

我有一个用户控件,它使用页面初始化中的以下代码动态加载到页面中.

Dim oCtl As Object
oCtl = LoadControl("~/Controls/UserControl1.ascx")

oCtl.Id = "UserControl11"
PlaceHolder1.Controls.Clear()
PlaceHolder1.Controls.Add(oCtl)
Run Code Online (Sandbox Code Playgroud)

用户控件还包含一个按钮,我无法捕获用户控件中的按钮单击.

Adr*_*ark 10

你正在做的一些事情都是不需要的,可能会导致你的问题.

这些是:

  1. 无需将控制对象存储在会话中.Control本身应该使用ViewState和Session State来存储所需的信息,而不是整个实例.
  2. 创建控件时,不应检查PostBack.每次都必须创建它以允许ViewState工作并且要连接事件.
  3. 加载ViewState后加载的控件通常无法正常运行,因此请尽可能避免在Page Load事件期间加载.

这段代码适合我:


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>
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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" />
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)


小智 5

在.NET进入页面生命周期的"回发事件处理"步骤之前,您必须确保控件存在于页面上.由于控件是动态添加的,因此您必须确保在每个帖子上重新创建该控件,以便它可以找到触发事件的控件.


Joe*_*orn 1

几个问题:

  1. 在页面生命周期的哪个点加载控件?
  2. 事件处理程序代码在哪里?在控件本身中还是尝试将其连接到页面?
  3. 到目前为止,您为举办该活动做了哪些工作?

最后,.Net 的样式指南特别建议不要使用任何 Hugarian 前缀,例如 oCtl 中的 o,并且您应该将其键入为 Control 而不是对象。