在ASP.NET的代码隐藏中访问用户控件

本文关键字:访问 用户 控件 隐藏 代码 ASP NET | 更新日期: 2023-09-27 18:11:47

这个问题是针对ASP的。净大师。我快疯了。

我继承了一个ASP。NET Web Forms应用程序。这个应用程序使用一个复杂的嵌套用户控件的结构。虽然很复杂,但在这种情况下似乎是必要的。无论如何,我有一个使用单个UserControl的页面。我们将其命名为UserControl根控制。这个UserControl定义如下:

widget.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="widget.ascx.cs" Inherits="resources_userControls_widget" %>
<div>
  <asp:Panel ID="bodyPanel" runat="server" />
</div>

widget.ascx.cs

public partial class resources_userControls_widget : System.Web.UI.UserControl
{
    private string source = string.Empty;
    public string Source
    {
        get { return source; }
        set { source = value; }
    }
    private string parameter1 = string.Empty;
    public string Parameter1
    {
        get { return parameter1; }
        set { parameter1 = value; }
    }
    private DataTable records = new DataTable();
    public DataTable Records
    {
        get { return records; }
        set { records = value; }
    }
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        UserControl userControl = LoadControl(source) as UserControl;
        if (parameter1.Length > 0)
            userControl.Attributes.Add("parameter1", parameter1);
        bodyPanel.Controls.Add(userControl);
    }
    private void InsertUserControl(string filename)
    {
    }
}

在我的应用程序中,我使用的是widget。Ascx以以下方式: page.aspx

<uc:Widget ID="myWidget" runat="server"  Source="/userControls/widgets/info.ascx" />

page.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
  DataTable table = GetData();
  myWidget.Records = table;
}

请注意如何信息。ascx被设置为我们想要加载的UserControl。这种方法在这种情况下是必要的。我已经删除了证明它专注于问题的无关代码。无论如何,在info. asx .cs中我有以下内容:

info.ascx.cs

protected void Page_Load(object sender, EventArgs e)
{
  // Here's the problem
  // this.Parent.Parent is a widget.ascx instance.
  // However, I cannot access the Widget class. I want to be able to do this
  // Widget widget = (Widget)(this.Parent.Parent);
  // DataTable table = widget.Records;
}

我真的需要从父用户控件获得"记录"属性的值。不幸的是,我似乎无法从代码隐藏中访问Widget类。在编译时是否有一些我不知道的关于UserControl可见性的规则?如何从info. asx .cs的代码后端访问Widget类?

谢谢!

在ASP.NET的代码隐藏中访问用户控件

首先需要创建一个接口,并将其实现到Widget用户控件类。

例如,

public interface IRecord
{
    DataTable Records {get;set;}
} 
public partial class resources_userControls_widget : System.Web.UI.UserControl, IRecord
{
 ...
}

在info . asx .cs后面的代码中,

protected void Page_Load(object sender, EventArgs e)
{
  // Here's the problem
  // this.Parent.Parent is a widget.ascx instance.
  // However, I cannot access the Widget class. I want to be able to do this
  // Widget widget = (Widget)(this.Parent.Parent);
  // DataTable table = widget.Records;
  IRecord record=this.Parent.Parent;
  DataTable table = widget.Records;
}

在你的情况下,也许最好使用一些服务器对象,如ViewState或Session。在页面上的DataTable中填充它,并在Page_load事件处理程序中获取它。