0

希望这足够清楚。

我对这一切都很陌生。

我有一个 asp.net 和 c# 项目,在 app_code 我有一个类 userInterface.cs,我需要做的是以下内容:

在那个课程中,我需要获得某个页面

新页面.aspx

, 并修改该页面上的一些 asp 元素。

目前我有这个:

Page p = (Page)HttpContext.Current.Handler;    

不知道我还需要什么才能获取该页面。我想要的页面称为NewPage.aspx。

我将不胜感激任何答案。

即使是谷歌搜索的东西也会很棒。我不知道从....开始

4

5 回答 5

2

您可以在 App_Code 类中创建方法,并从代码后面的任何事件中调用此方法。您可以将 GridView 或完整的 Page 传递给此方法。

这是位于您的代码隐藏文件中的 Page_Load 事件。

protected void Page_Load(object sender, EventArgs e)
{
    UserInterface.UpdateGrid(ref GridView1);
}

这是位于 .cs 文件中的静态方法。

public static void UpdateGrid(ref GridView view)
{
    // update your GridView here
}
于 2011-08-23T11:18:02.217 回答
1

我认为您不能在您的网站中执行此操作,但您可以在App_Code文件中创建一个方法,您可以从您的页面调用该方法并将控制权传递给该方法以从那里访问它。

更新

我是你的App_Code文件

using System.Web.UI.WebControls;

public static void AddColumn(ref GridView gv)
    {
        BoundField field1=new BoundField();
        field1.HeaderText="Header Text";
        field1.DataField = "DataFieldName";
        gv.Columns.Add(field1);


        BoundField  field2 = new BoundField();
        field2.HeaderText = "Header Text";
        field2.DataField = "DataFieldName";
        gv.Columns.Add(field2);
    }

在您的页面中

Test.AddColumn(ref MyGridView);
MyGridView.DataSource = names;// assign your datasource here
MyGridView.DataBind();
于 2011-08-23T10:48:45.833 回答
0

您也许可以通过 HttpContext 访问该页面,但这可能不是一个好方法。正如其他海报所指出的,只需使用一种方法并传入对控件的引用即可。

不过,要回答您的问题,您可以尝试以下方法:

if (HttpContext.Current.Handler is Page)
{
    Page currentPage = (Page)HttpContext.Current.Handler;
    if (currentPage != null)
    {
        //depending on where the control is located, you may need to use recursion
        GridView gridView = currentPage.FindControl("GridView1");
    }
}

我必须重申,由于种种原因,这可能不是一个好方法。不过,我确实希望有人回答您的实际问题,所以就是这样。

于 2011-08-23T18:57:14.967 回答
0

如果您尝试从 App_Code 类访问 .aspx 页面,则说明您的代码有问题。你不应该这样做。App_Code 中的类用于为您的 .aspx 页面提供服务,而不是反向。例如,在 App_Code 中,您将保留实用程序类。

于 2011-08-23T11:08:40.517 回答
0

如果内容页 (.aspx) 绑定在 Master Page 下。您需要考虑在内容页面内定位控件的父控件。例如,如果母版页包含内容占位符,并且在该占位符内您正在绑定页面,则必须首先找到内容占位符。

Page p = HttpContext.Current.Handler as Page;
Label lbl = p.Form.FindControl("ContentPlaceHolder1").FindControl("UpdatePanel1").FindControl("lblTest") as Label

在编译响应请求时,ASP.Net 总是通过母版页文件(如果有的话)到达内容页。因此,在从类中请求任何 .aspx 文件下的页面控件时,必须首先在母版页中找到父控件。

于 2016-07-27T15:29:30.677 回答