Accessing page controls from a separate class
I'm wondering how I can go about accessing page controls from a separate class I've made. I've tried a few things I found using google, but no luck :(
What I'm trying to do is keep a function that is used often, in a global class.
The function then accesses a page literal and calls ScriptManager.RegisterStartupScript. I was hoping this is possible, so then thi开发者_运维问答s function wouldn't have to be copied to all of the pages.
I'm not sure whether I understood you correctly - if not, post some sample code.
If you have your page ex Default and the code behind like this:
public partial class Default : System.Web.UI.Page
{
//Some methods
}
You can make a helper class like this:
class Helpers
{
public static void YourHelperMethod(Default page)
{
//You can access your controls here like:
page.someLabelControl.Text = "Some text";
}
}
And if you want it to work with all pages, you can "find" the control like the following. You should, however, use Master pages and the code behind if there is something that need to be done on all pages.
class Helpers
{
public static void YourHelperMethod(Page page)
{
//You can access your controls here like:
Label label = page.FindControl("labelName") as Label;
if (label == null)
//The control could not be found
label.Text = "Some text";
}
}
Your method should accept a Literal as parameter. Call the method with the labels you want to modify. Be aware that the literal you are trying to access must have been created before in the lifecycle
I am not sure that I understand your task correctly. Anyway, if you have a Page object and a name of the control, you should access, the code should be:
class Helper
{
public static void SomeHelperMethod(Default page, string controlName)
{
Control control = page.Form.FindControl(controlName);
if(control != null) {
// your code here
}
}
}
精彩评论