In asp.net, how to reference page controls in a custom base page class

I have a large number of pages .aspx(asp.net 4, C #) that all inherit from a custom base page class (which inherits from the System.Web.UI.Page class).

By convention, all of these pages have the same set of controls (for example, multiple text fields with the same identifier).

I would like to put some generic code in a custom base page class that extracts values .Textfrom these controls on the page.

Please note that this is not a MasterPage setting. I have a custom base page class, and then a series of pages that inherit from this base class.

How can I link to text fields on a page from a base class?

+3
source share
3 answers

If they all have the same set of controls on them by convention, why not move the controls to the base class?

Alternatively, you can create an interface that includes a common set of controls, and then implement that interface in all your aspx.cs codebehinds. This will allow you to have some aspx pages that violate the convention. You can use "this" as an interface, in the base class, and if its value is not null, change the controls. For instance:

IControlSet controlSet = this as IControlSet;

if(controlSet != null)
{
    controlSet.Name.Text = "someName";
}
+2
source

, , . , .

protected abstract TextBox MyTextBox { get; }

MyTextBox.

, , PageBase, , .

EDIT:

. , MyPageBase, HomePage.aspx = "TextBox1"

public abstract class MyPageBase : Page
{
    protected abstract TextBox MyTextBox { get; }
}

:

public partial class HomePage : MyPageBase
{
    protected override TextBox MyTextBox
    {
        get 
        {
             return this.TextBox1;
        }
    }
}

, . , , .

this.MyTextBox.Text = "Change the text";

, , , getter/setter text . , .

+2

Page.FindControl("ControlID").

:

var txt = Page.FindControl("TextBox1") as TextBox;
if (txt != null)
{
    //found the textbox
    //...
}

Depending on where the controls are located in the form, in particular if they are in a container that implements the interface INamingContainer, you may need to make a recursive method FindControl()that can traverse the control hierarchy.

public Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id)
        return root;

    foreach (Control control in root.Controls)
    {
        Control foundControl = FindControlRecursive(control, id);
        if (foundControl != null)
            return foundControl;
    }

    return null;
}
+2
source

All Articles