将数据传递给动态创建的ascx用户控件

时间:2014-09-30 10:58:07

标签: c# asp.net

我想显示用户控件,它根据传递给它的值产生不同的数据集。

没有。 UserControls在运行时决定

  • 现在它在ascx.cs
  • 的Page_Load中点击

Default.aspx的

<%@ Register Src="~/UserControl/SquareEUA.ascx" TagName="Square" TagPrefix="EUA" %>

<body>
     <div id="divControls" runat="server"></div>
</body>

Default.aspx.cs

    protected void Page_Load(object sender, EventArgs e)
    {
    string[] Property;
    foreach (string sPropID in Property)
    {
SquareEUA userControl = (SquareEUA)Page.LoadControl("~/UserControl/SquareEUA.ascx"); 
        userControl.ID = "MyControl_" + sPropID.Trim();
        userControl.sCustID = CustomerID; 
        userControl.sCustPropID = sPropID.Trim(); 
        userControl.Visible = true;
        divControls.Controls.Add(userControl); 
        userControl.Dispose();
    }
    }

SquareEUA.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SquareEUA.ascx.cs" Inherits="UserControl.SquareEUA" %>
<div>
     // Some HTML Markup
</div>

SquareEUA.ascx.cs

public partial class SquareEUA : System.Web.UI.UserControl
{
public string sCustID { get; set; }
public string sCustPropID { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Some Code    
        // Didnt Hit Breakpoint Here;
    }
}        

1 个答案:

答案 0 :(得分:0)

您需要将您的usercontrol转换为实际的SquareEUA类才能访问该类的属性

SquareEUA userControl = (SquareEUA)(Page.LoadControl("~/UserControl/SquareEUA.ascx"));

应该做的伎俩(你应该添加一些错误处理,空检查等)

编辑:似乎我错过了一个括号(Page ...