gpt4 book ai didi

.net - 使用 LoadControl(Type, Object()) 以编程方式加载用户控件

转载 作者:行者123 更新时间:2023-12-04 12:35:41 26 4
gpt4 key购买 nike

我正在动态地将 Web 用户控件添加到页面。使用 LoadControl仅采用指向 .ascx 的虚拟路径的方法工作得很好。但是, LoadControl 的过载需要一个类型和一个参数数组让我有些头疼。

Web 用户控件按预期实例化,但 Web 用户控件中包含的控件为空,并且在尝试使用它们时立即出现异常。奇怪,因为它在使用 LoadControl 的第一个版本时有效.

Web 用户控件,简单,带有 Literal控制:

<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="MyControl.ascx.vb" Inherits="MyControl" %>
<asp:Literal ID="myLiteral" runat="server"></asp:Literal>

控件背后的代码:
Public Class MyControl
Inherits System.Web.UI.UserControl

Public Property Data As MyData

Public Sub New()

End Sub

Public Sub New(data As MyData)
Me.Data = data
End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
myLiteral.Text = Data.ID ' The Literal is null, but ONLY when I use the second LoadControl() method!
End Sub

End Class

以及来自 .aspx的相关代码我试图从中动态加载控件:
Private Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
Dim x = LoadControl(GetType(MyControl), New Object() {New MyData With {.ID = 117}})
Page.Controls.Add(x)

' Using LoadControl("MyControl.ascx") works as expected!
End Sub

最佳答案

this article 的帮助下通过 Steven Robbins,我最终得到了一个非常方便的扩展方法:

Imports System.Runtime.CompilerServices
Imports System.Web.UI
Imports System.Reflection

Module LoadControls
<Extension()> _
Public Function LoadControl(templateControl As TemplateControl, virtualPath As String, ParamArray constructorParams() As Object) As UserControl
Dim control = TryCast(templateControl.LoadControl(virtualPath), UserControl)
Dim paramTypes = constructorParams.Select(Function(p) p.GetType()).ToArray
Dim constructor = control.GetType().BaseType.GetConstructor(paramTypes)

If constructor Is Nothing Then ' Nothing if no such constructor was found.
Throw New ArgumentException(String.Format("No constructor for control '{0}' with {1} parameter(s) were found.", virtualPath, paramTypes.Count))
Else
constructor.Invoke(control, constructorParams)
End If

Return control
End Function

End Module

关于.net - 使用 LoadControl(Type, Object()) 以编程方式加载用户控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9446307/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com