简体   繁体   中英

How can I find a control in C# from a class file?

I am having a heck of time here. I have a class file and I need to reference a control from a web page in it. I've found some examples around the web, but something is not working correctly. Here's the relevant C#:

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

What I'm trying to do is bind some data to this DropDownList in my class file. The problem is that at the third line there, I get the old:

Object reference not set to an instance of an object.

If I return the FieldCount of the SqlDataReader , I get the right number of fields, so I think it's got data; I'm just not finding the control, I guess. How can I find the control ddlCrimeType in my class file?

Let me know if there's anything else you need to know.

Update:

The control is in a content page. When I wrote similar code in my page's codebehind to do the same thing, I had to do this:

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

I just need to figure out how to do that in my class file. Right now, I'm told:

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

Okay, as it turns out, I needed to reference the control appropriately for a master page / content page relationship. ddl was remaining null in my original code because I wasn't finding a control from the base of the master page. This is the actual successful code:

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();

Also, I'm passing the ID of the control to the method instead of specifying it like in my previous code.

Thanks to all who helped! Have a great day!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM