且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从代码后面添加用户控件

更新时间:2023-12-06 12:46:16

我更喜欢javascript / ajax解决方案,但我认为有您的代码没有任何问题。

I prefer javascript / ajax solution but I think there is nothing wrong with your code.

我做了一个小例子。这是与你一样的解决方案。优点是只在点击的情况下加载控件。

I did small example. Here is same solution as you have. Advantage is that control is loaded only in case of click.

public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnLink_Click(object sender, EventArgs e)
        {
            var uc = (UserControl)Page.LoadControl("~/WebUserControl1.ascx");
            pnl.Controls.Add(uc);            
        }
    }

以下是在Page_Load事件中加载用户控件的示例并且在单击(btnLink_Click)的情况下,用户控件被添加到面板。它与您的解决方案相同,但即使不需要,也可以加载用户控件(在内存中处理而不是处理)。

Here is example where user control is loaded in Page_Load event and in case of click (btnLink_Click) user control is added to panel. It works same as your solution but user control can be loaded (processed in memory not redered) even if is not needed.

public partial class Default : System.Web.UI.Page
    {
        UserControl uc; 
        protected void Page_Load(object sender, EventArgs e)
        {
           if(IsPostBack) // This condition is not needed but we know that click is always postback
            uc = (UserControl)Page.LoadControl("~/WebUserControl1.ascx");
        }

        protected void btnLink_Click(object sender, EventArgs e)
        {

            pnl.Controls.Add(uc);            
        }
    }

这是我更喜欢的解决方案,它基于可见属性。如果用户控件不可见,则不会将其呈现为输出。当然,如果桌子上有很多单元格作为对照容器而不是面板,那么它不是很实用。

Here is solution which I prefer, it's based on visible property. In case that user control is not visible it's not rendered to output. Sure it's not very practival in case of table with lot of cells as a control container instead of panel.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<%@ Register Src="~/WebUserControl1.ascx" TagName="ucrCtrl" TagPrefix="ctr"  %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button ID="btnLink" runat="server" Text="Add" OnClick="btnLink_Click" />
        <asp:Panel runat="server" ID="pnl">
            <ctr:ucrCtrl runat="server" ID="usrCtrl" Visible="false" />
        </asp:Panel>
    </div>
    </form>
</body>
</html>

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnLink_Click(object sender, EventArgs e)
        {
            usrCtrl.Visible = true;     
        }
    }
}