【问题标题】:Pass value from Page to User Control将值从页面传递到用户控件
【发布时间】:2013-05-21 01:36:52
【问题描述】:

我有一个在 Default.aspx 页面中调用的自定义用户控件:

<myPrefix:myTagName ID="category" runat="server" />

自定义用户控件的代码:

namespace WebApplication3.inc.controls {
    public partial class myTag : System.Web.UI.UserControl {
        public String id;
        public String name;
        public String value;
        public Hashtable attributes;

        protected void Page_Load(object sender, EventArgs e) {
            if (this.id != null)
                this.attributes["id"] = this.id;
            if (this.name != null)
                this.attributes["name"] = this.name;
            if (this.value != null)
                this.attributes["value"] = this.value;
        }
    }
}

在 Default.aspx.cs 代码中,我想设置这个标签的值:

this.articleCategory.value = this.currentArticle.Category.ToString();

我在最后一行的“值”处收到此错误:

'System.Web.UI.UserControl' 没有 包含“价值”的定义和 没有扩展方法“值”接受 类型的第一个参数 'System.Web.UI.UserControl' 可能是 找到(您是否缺少使用 指令还是程序集引用?)

我看到的所有演示似乎都表明这应该有效。我错过了什么吗?

【问题讨论】:

    标签: c# parameter-passing user-controls


    【解决方案1】:

    错误消息表明您的页面类中对控件实例的引用当前是System.Web.UI.UserControl 类型。它必须是WebApplication3.inc.controls.myTag 类型才能访问value 成员。解决此问题的一种方法是将变量的声明移动到代码隐藏文件中,而不是让 Visual Studio 自动生成变量,但执行此操作的确切方式取决于您的项目设置以及您在页面中包含控件的方式。

    【讨论】:

      【解决方案2】:

      这可能是因为您在错误的时间调用它,首先在页面上调用Page_Load,然后在页面上调用所有子控件。也许您只需要更改控件以在Init 而不是Page_Load 上进行初始化

      【讨论】:

      • 其实乔纳斯回答的可能性更大
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      相关资源
      最近更新 更多