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:
TextBox txt = (TextBox)Page.Controls[0].Controls[3].Controls[48].Controls[6]
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.
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.
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With