处理列表视图中的用户控件事件

Handling events of usercontrols within listview(处理列表视图中的用户控件事件)

本文介绍了处理列表视图中的用户控件事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的用户控件,它会在按钮单击时引发事件

I have a simple usercontrol which raises an event on button click

Public Class UcPaymentCheque
    Inherits System.Web.UI.UserControl

    Public Event OnCancelClick()

    Private Sub btnCancelPayment_Click(sender As Object, e As System.EventArgs) Handles btnCancelPayment.Click
        RaiseEvent OnCancelClick()
    End Sub
End Class

此用户控件在列表视图中使用

This usercontrol is used within a listview

<asp:ListView ID="lvwNonTpProducts" runat="server" ItemPlaceholderID="ItemPlaceholder">
    <LayoutTemplate>
        <asp:PlaceHolder ID="ItemPlaceholder" runat="server" />
    </LayoutTemplate>
    <ItemTemplate>
        <TPCustomControl:UcPaymentCheque ID="UcTPPaymentCheque" runat="server" Visible="false" />
    </ItemTemplate>
</asp:ListView>

页面加载时数据绑定

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Page.IsPostBack Then

    Else
        BuildPage()
    End If
End Sub

应该在什么时候添加处理程序?我已经像这样摆弄了 ondatabound 事件;

At what point should add the handler? I have fiddled with the ondatabound event like so;

Private Sub lvwNonTpProducts_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles lvwNonTpProducts.ItemDataBound
    Dim UcTPPaymentCheque = DirectCast(e.Item.FindControl("UcTPPaymentCheque"), UcPaymentCheque)
    AddHandler UcTPPaymentCheque.OnCancelClick, AddressOf OnCancelClick
End Sub

但这不起作用,我猜是数据绑定问题???

but this does not work and am guess at a databound issue???

推荐答案

你可以在这里查看我对类似问题的回答:创建和监听事件

You can check out my response to a similar question here: creating and listening for events

本质上,您希望用户控件引发自己的事件,如下所示:

Essentially, you want a user control to raise its own event, like this:

Partial Class myControl
    Inherits System.Web.UI.UserControl
    Public Event MyEvent As EventHandler

    'your button click event
    Protected Sub bnt_click(ByVal sender As Object, ByVal e As EventArgs)
      'do stuff
      'now raise the event
       RaiseEvent MyEvent (Me, New EventArgs)
    end sub
end class

在此示例中,我在用户单击用户控件中的按钮时引发事件.您可以轻松地在任何地方引发事件,例如当控件加载时,使用计时器等等.

In this example, I raise the event when the user clicks a button within the user control. You can easily raise the event anywhere, such as when the control loads, using a timer, whatever.

然后,在主页面中,你想要和一个事件处理程序给用户控件,像这样:

Then, in the main page, you want to and an event handler to the user control, like this:

<mc:myControlrunat="server" ID="myControl1" OnMyEvent="myControl_MyEvent"  /> 

现在,在后面的代码中,您可以添加事件,如下所示:

Now, in the code behind, you can add the event, like this:

Protected Sub myControl_MyEvent(ByVal sender As Object, ByVal e As EventArgs)
 'do stuff 
end sub

这篇关于处理列表视图中的用户控件事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:处理列表视图中的用户控件事件