在面板中呈现asp.net用户控件

时间:2018-10-16 10:00:02

标签: asp.net vb.net user-controls

我创建了这个asp.net用户控件(仅是此堆栈溢出后的示例)

HTML:

<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="ucBTN.ascx.vb" Inherits="EBC_SAK_MVV_BTN.web.ucBTN" %>

<div>
    <asp:Button ID="btnLeft" runat="server" Width="200" Height="100" CssClass="btn btn-sq-lg btn-primary" Text="Button-Left" />
    <asp:Button ID="btnMiddle" runat="server" Width="200" Height="100" CssClass="btn btn-sq-lg btn-primary" Text="Button-Middle" />
    <asp:Button ID="btnRight" runat="server" Width="200" Height="100" CssClass="btn btn-sq-lg btn-primary" Text="Button-Right" />
</div>

后面的代码:

Public Class ucBTN
    Inherits System.Web.UI.UserControl
    Public Property TextLeft As String
    Public Property TextMiddle As String
    Public Property TextRight As String
End Class

当我在页面中使用此用户控件时,它会起作用(test.aspx):

<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/EBC.Master" CodeBehind="TEST.aspx.vb" Inherits="EBC_SAK_MVV_BTN.web.TEST" %>

<%@ Register Src="~/ucBTN.ascx" TagPrefix="uc1" TagName="ucBTN" %>
<uc1:ucBTN runat="server" ID="myBTN" />

但是,当我在页面上添加面板并将用户控件添加到该面板时,它保持空白:

HTML:

<asp:Panel ID="Panel1" runat="server"></asp:Panel>

后面的代码:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim BTN As New ucBTN
BTN.TextLeft = "LEFT"
BTN.TextMiddle = "MIDDLE"
BTN.TextRight = "RIGHT"
Panel1.Controls.Add(BTN)
End Sub

我想在运行时创建许多这样的控件-如何将它们添加到面板中?

1 个答案:

答案 0 :(得分:2)

使用PlaceHolder代替面板

在用户控件中使用:

  <asp:PlaceHolder ID="PlaceHolder1" runat="server"> 

在使用后的代码中:

 PlaceHolder1.Controls.Add(BTN)