在父页面中覆盖ASCX控件方法

时间:2016-02-16 15:42:51

标签: asp.net vb.net webforms override

我有一个ASCX用户控件,正在大约60个Web表单页面中使用。此控件基本上呈现一系列嵌套下拉列表。

在控件内部,填充最终列表的方法如下:

Public Sub PopulateList()
   Dim dt as DataTable = MyDAL.GetListValues()
   For each dr as DataRow in dt.Rows
      Dim li as new ListItem
      ' ... 
      myDDL.Items.Add(li)
   Next
End Sub

在少数几页中,我需要这种方法略有不同(列表项中填充了更多详细信息,来自不同的表)。

控件的父页面是否有可能以某种方式覆盖方法?我在各种MSDN页面上阅读了有关覆盖的内容,但无法弄清楚这一点。我可以将方法声明为......

 Public Overridable Sub PopulateList()

...但是在VS2015中,当我尝试使用Public Overrides创建覆盖方法时,Intellisense菜单不包含对用户控件或方法的任何引用。我认为这是因为控件实际上并没有被页面继承?

这可能吗,或者还有其他方法吗?

1 个答案:

答案 0 :(得分:1)

你不能"覆盖"父页面中的方法,因为页面不会从您的控件类继承。

您可以创建一个事件处理程序,或者传入一个委托来修改该方法的行为。

例如:

Public Class Test1

    Dim t2 As New Test2

    Sub New()

        ' Call populateList with an action handler
        t2.PopulateList(Sub(ddl)
                        ' Do your logic here

                        Dim dt As DataTable = MyDAL.GetListValues()
                        For Each dr As DataRow In dt.Rows
                            Dim li As New ListItem
                            ' ... 
                            ddl.Items.Add(li)
                        Next

                    End Sub)

    End Sub


End Class

Public Class Test2
    Public Sub PopulateList(Optional handler As Action(Of DropDownList) = Nothing)

        If handler Is Nothing Then
            ' Default behavior
            Dim dt As DataTable = MyDAL.GetListValues()
            For Each dr As DataRow In dt.Rows
                Dim li As New ListItem
                ' ... 
                myDDL.Items.Add(li)
            Next

        Else

            ' Invoke action handler and pass a reference to the dropdown you want to add items to
            handler(myDDL)

        End If

    End Sub
End Class

使用事件的示例:

Event MyCustomEvent As EventHandler(Of MyCustomEventArgs)

Public Sub PopulateList()

    Dim args As New MyCustomEventArgs()
    args.ListObject = myDDL
    RaiseEvent MyCustomEvent(Me, args)

    ' Do default behavior if not handled by event code
    If Not args.Handled Then

        Dim dt As DataTable = MyDAL.GetListValues()
        For Each dr As DataRow In dt.Rows
            Dim li As New ListItem
            ' ... 
            myDDL.Items.Add(li)
        Next

    End If


End Sub

自定义事件args类:

Public Class MyCustomEventArgs
    Inherits EventArgs

    Public Property Handled As Boolean
    Public Property ListObject As DropDownList
End Class

处理您的信息页:

Protected Sub MyControl_MyCustomEvent(sender As Object, e As MyCustomEventArgs) Handles MyControl.MyCustomEvent

    e.Handled = True

    ' Do work on your list
    Dim mylist = e.ListObject


End Sub