如何从类文件中找到c#中的控件?

本文关键字:控件 文件 | 更新日期: 2023-09-27 18:05:34

我在这里有很多时间。我有一个类文件,我需要从它的网页引用控件。我在网上找到了一些例子,但是有些东西不能正常工作。下面是相关的c#:

Page page = (Page)HttpContext.Current.Handler;
DropDownList ddl = (DropDownList)page.FindControl("ddlCrimeType");
ddl.DataSource = read; // read is a SqlDataReader.
ddl.DataBind();

我要做的是绑定一些数据到这个DropDownList在我的类文件。问题是,在第三行,我得到了旧的:

对象引用未设置为对象的实例。

如果我返回SqlDataReaderFieldCount,我得到了正确的字段数,所以我认为它有数据;我只是找不到控制自己的方法。我如何在我的类文件中找到控件ddlCrimeType ?

如果你还需要知道什么,请告诉我。

更新:

控件位于内容页中。当我在页面的后台代码中编写类似的代码来做同样的事情时,我必须这样做:

DropDownList ddl = (DropDownList)Master.FindControl("ContentPlaceHolder1").FindControl("ddlCrimeType");

我只需要弄清楚如何在我的类文件中做到这一点。现在,我被告知:

The name 'Master' does not exist in the current context.

如何从类文件中找到c#中的控件?

好的,事实证明,我需要为母版页/内容页关系适当地引用控件。ddl在我的原始代码中保持为空,因为我没有从母版页的基础找到控件。这是实际成功的代码:

var pageHandler = HttpContext.Current.CurrentHandler;
Control ctrl = ((System.Web.UI.Page)pageHandler).Master.FindControl("ContentPlaceHolder1").FindControl(strControlIDToBind);
DropDownList ddl = (DropDownList)((System.Web.UI.Page)pageHandler).Master.FindControl("ContentPlaceHolder1").FindControl(strControlIDToBind);
ddl.DataSource = read;
ddl.DataBind();

另外,我将控件的ID传递给方法,而不是像前面的代码那样指定它。

感谢所有帮助过我的人!祝你今天愉快!