自从我想到“如何通过用户控件的按钮单击触发我的事件?”以来已经 4 小时了。答案很快就来了:“我可以捕获按钮的点击事件并从那里提升我的!” 经过 4 小时的调试和调试以及更多的调试和页面生命周期、更多的调试和更多的断点等等,我求助于 GREAT STACKOVERFLOW(bows)。所以这个问题很简单;为什么我不能捕获放置在用户控件内的按钮的 onclick 事件,以便触发我的事件?至于代码:这是 ascx :
<%@ Control Language="vb" AutoEventWireup="true" CodeBehind="CosmaButton.ascx.vb" Inherits="Comanda.CosmaButton" %>
用户控件背后的代码:
Public Class CosmaButton
Inherits System.Web.UI.UserControl
Public Event ClickBtn As EventHandler
Private _title As String = "test"
Private _width As Integer
Private WithEvents _button As New Button
Protected Overrides Sub OnInit(e As EventArgs)
MyBase.OnInit(e)
End Sub
Protected Overrides Sub OnLoad(e As EventArgs)
MyBase.OnLoad(e)
End Sub
Protected Overrides Sub OnPreRender(e As EventArgs)
_button.CssClass = "styled"
_button.Text = _title
_button.Attributes("runat") = "server"
If _width > 0 Then
_button.Width = _width
End If
Me.Controls.Add(_button)
MyBase.OnPreRender(e)
End Sub
Protected Sub _button_Clicked(sender As Object, e As EventArgs)
RaiseEvent ClickBtn(Nothing, Nothing)
End Sub
End Class
最后是 aspx 页面的代码隐藏:
Public Class Login1
Inherits System.Web.UI.Page
Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
AddHandler btn.ClickBtn, AddressOf btn_Click
End Sub
Protected Sub btn_Click(sender As Object, e As EventArgs) Handles btn.ClickBtn
End Sub
End Class
PS做了我的功课并搜索了与此问题相关的所有帖子,发现: http: //www.codeproject.com/Articles/33874/Capture-Button-s-Click-Event-of-User-Control-in-th有点令人沮丧,因为我在这个人的帖子中跟随并重新关注并一步一步地进行,但效果相同。没有可怕的点击事件!
编辑1:
为单击事件添加了处理程序,因此更新的代码隐藏版本如下:
Public Class CosmaButton
Inherits System.Web.UI.UserControl
Public Event ClickBtn As EventHandler
Private _title As String = "test"
Private _width As Integer
Private WithEvents _button As New Button
Protected Overrides Sub OnInit(e As EventArgs)
Me.Controls.Add(_button)
AddHandler _button.Click, AddressOf _button_Clicked
MyBase.OnInit(e)
End Sub
Protected Overrides Sub OnLoad(e As EventArgs)
MyBase.OnLoad(e)
End Sub
Protected Overrides Sub OnPreRender(e As EventArgs)
_button.CssClass = "styled"
_button.Text = _title
_button.Attributes("runat") = "server"
If _width > 0 Then
_button.Width = _width
End If
MyBase.OnPreRender(e)
End Sub
Protected Sub _button_Clicked(sender As Object, e As EventArgs)
RaiseEvent ClickBtn(Nothing, Nothing)
End Sub
End Class
仍然没有。我之前多次添加了处理程序,但是在阅读并尝试了提到的帖子之后,我在我的用户控件中添加了一个 asp:button 标签,但没有成功,之后我发布了这个问题。