1

我正在将用户控件动态加载到页面上。我通常是一个 vb.net 人,通常可以过得去,但这让我很难过。我试图在加载之前将变量从页面传递给控件。

这里是我调用控件的地方:

    Control webUserControl = (Control)Page.LoadControl("~/controls/carousel-guards.ascx");

    phGuardsList.Controls.Add(webUserControl);

我在 carousel-guards.ascx 上放置了以下属性:

public String PostCode
        {
            get
            {
                return this.PostCode;
            }
            set
            {
                this.PostCode = value;
            }
        }

但我似乎没有可用的 webUserControl.PostCode。

任何帮助将不胜感激

编辑 -当然,我必须引用控件。傻我!但是它不允许我用 carousel_guards 调用它:Error 96 The type or namespace name 'carousel_guards' could not be found (are you missing a using directive or an assembly reference?) C:\Development\Guards247\g247 Test\FindGuard.aspx.cs 197 13 g247 Test

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace g247_Test.controls
{
    public partial class carousel_guards : System.Web.UI.UserControl
    {

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public String PostCode
        {
            get
            {
                return this.PostCode;
            }
            set
            {
                this.PostCode = value;
            }
        }
    }
}
4

3 回答 3

1

您需要使用页面的类名称才能工作。

var webUserControl = (carousel_guards)Page.LoadControl("~/controls/carousel-guards.ascx");

// now works
webUserControl.PostCode = "17673";
phGuardsList.Controls.Add(webUserControl);

如果您没有包含控件的引用并且没有找到类的名称,您可以在 aspx 上插入该行

<%@ Reference Control="~/controls/carousel-guards.ascx" %>

或者只是将其拖放到页面内,以进行引用,然后删除实际控件,因为您使其成为动态的。

于 2012-11-13T11:11:19.320 回答
0

您无法从控件访问该属性,因为您将加载的控件转换为Control. 您应该将其转换为您的控件类型。如果您的 Control 类名称是,CarouselGuards那么您可以执行以下操作:

CarouselGuards webUserControl = (CarouselGuards)Page.LoadControl("~/controls/carousel-guards.ascx");

然后您可以访问该属性。

webUserControl.PostCode = "123";
于 2012-11-13T11:11:26.877 回答
0

为您的控件类型使用强制转换,CarouselGuards而不是Control

CarouselGuards webUserControl = (CarouselGuards)Page.LoadControl("~/controls/carousel-guards.ascx");
webUserControl.PostCode = "XXXX";

作为旁注,不要忘记对象的检查空控件。

于 2012-11-13T11:12:16.043 回答