Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a control in a webform

I have a Web content form and need to access a control inside the content panel. I know of two ways to access the control:

  1. TextBox txt = (TextBox)Page.Controls[0].Controls[3].Controls[48].Controls[6]
  2. By writing a recursive function that searches through all controls.

Is there any other easier way, since Page.FindControl doesn’t work in this instance. The reason I am asking is it feels to me like the Page object or the Content Panel object should have a method to find a child control, but can’t find anything like it.

like image 903
fARcRY Avatar asked Mar 06 '09 16:03

fARcRY


People also ask

How can you add controls to your Web form?

first add TextBox control on web form from Toolbox, just select TextBox control in Toolbox and drag and drop on web form or make double click on TextBox control it will added on web form then add Button control on web form like shows below screen.

What is C# Find control?

FindControl(String)Searches the current naming container for a server control with the specified id parameter. public: virtual System::Web::UI::Control ^ FindControl(System::String ^ id); C# Copy. public virtual System.Web.UI.

What is web form and web form control?

Web Forms are web pages built on the ASP.NET Technology. It executes on the server and generates output to the browser. It is compatible to any browser to any language supported by . NET common language runtime. It is flexible and allows us to create and add custom controls.


1 Answers

I would like to change your GetControls function to a generic one as follows:

public static T GetControl<T>(this Control control, string id) where T:Control
{
    var result = control.Controls.Flatten(c => (c.GetType().IsSubclassOf(typeof(T))) && (c.ID == id)).SingleOrDefault();
    if (result == null)
        return null;
    return result as T;
}

And Then,

public static Control GetControl(this Control control, string id)
{
    return control.GetControl<Control>(id);
}

This way, the caller would call something like:

var button = Page.GetControl<Button>("MyButton");
like image 86
Sadra Abedinzadeh Avatar answered Sep 24 '22 15:09

Sadra Abedinzadeh