Find control in usercontrol from a Page ASP.NET - asp.net

I am loading a control to a page dynamically with LoadControl("src to file").
In the usercontrol i have a validator and some other controls that i would like to access from my page. I canät get it to work, null pointer exception.
Scenario is like this. I have a Edit.aspx page which loads the EditTemplate.ascx usercontroll. I would like to get information or find the controls in the EditTemplate from the Edit.aspx site.
I have tried exposing the controls and validators as properties but how do i access them from my Edit.aspx?
Example code:
Edit.aspx, the control is later added into a
Control control = LoadControl("src to ascx");
TemplatePlaceHolder.Controls.Add(control);
EditTemplate.ascx
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="CompanyImageFile" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
CodeBehind
public partial class EditTemplate : System.Web.UI.UserControl, IEditTemplate {
public RequiredFieldValidator Validator {
get { return this.RequiredFieldValidator1; }
set { this.RequiredFieldValidator1 = value; }
}
From the Edit.aspx site i would like to check the validators isValid property. Isvalid is set in a Save method.
The save button that saves the template is located in edit.aspx, so the post in done from that page.
So the question is how to get a hold of the property from the usercontrol in the edit.aspx page, where and how should this be done?
Thanks again.

Easiest way is to have the user control define properties like:
public IValidator SomeValidator {
get { return this.cuvValidator; }
set { this.cuvValidator = value; }
}
public string Text {
get { return this.txtText.Text; }
set { this.txtText.Text = value; }
}
Which your edit page can use.
HTH.

You can always use recursive approach. Check the solution on Steve Smith's blog:
Recursive-FindControl.

As mentioned in previous answers, I would expose any validators you must access from the parent ASPX page as properties in the user control.
public RequiredFieldValidator ValidatorToCheck
{
get { return this.rfvMyField; }
}
Then, you can dynamically add your user control to some placeholder (being sure to assign an ID to the user control).
// In my example, this is occurring in the Page_Load event
Control control = LoadControl("~/Controls/EditTemplate.ascx");
control.ID = "ucEditTemplate";
pnlControlHolder.Controls.Add(control); // the placeholder in my example is a panel
When you want to access the IsValid property on the given validator (presumably in your save action) you can do so as follows (being sure to cast the control to the appropriate type and using the ID you originally assigned to the user control):
EditTemplate control = (EditTemplate)pnlControlHolder.FindControl("ucEditTemplate");
if (control.ValidatorToCheck.IsValid)
{
// Some action
}

Related

ASP.NET Maintaining ViewState for controls inside a custom control template

I have a template property in my control declared as follows:
<TemplateContainer(GetType(GenericTemplateContainer)),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateInstance(TemplateInstance.Single)>
Property CustomTemplate As ITemplate
In my control's Init event I have the following:
If Me.CustomTemplate IsNot Nothing Then
Dim TemplateContainer As New GenericTemplateContainer
Me.CustomTemplate.InstantiateIn(TemplateContainer)
PlaceHolder.Controls.Add(TemplateContainer)
End If
This allows me to place controls in markup inside my template, but on a post back the controls inside the template are not holding their ViewState.
I have tried adding PersistChildren(True) attribute to CustomTemplate property but I cannot because it's not valid.
Are you putting the values into ViewState? From what I understand, you need to do that. Either that, or re-bind with the data on every postback.
Here's what I like to do inside User Controls. I apologize for this being C# and not VB, but I don't know VB:
public string Text {
get { return (string)ViewState["Text"]; }
set { ViewState["Text"] = value; }
}
Reference: https://weblogs.asp.net/infinitiesloop/Truly-Understanding-Viewstate

how to access ascx custom control property from masterpage.master.cs

I have this following property in my custom user control:
public string selectedtab
{
get
{
if (ViewState["AdminCurrentNavID"] != null)
{
return ViewState["AdminCurrentNavID"].ToString();
}
else {
isfirstload = true;
return null;
}
}
set { ViewState["AdminCurrentNavID"] = value; }
}
I am setting the value of it on my Page_Load() in ascx control. What i need to do is that after setting the value of this property I need to access it from masterpage.cs in code behind. you can see how currently I am trying to do in below code, but the issue is that I am not able to get the value i thing it is because the masterpage's Page_Load() rendering before the ascx control so I thats why I am getting null value, please help, thanks.
masterpage.cs:
usercontrols.mainmenu adminmenu = (usercontrols.mainmenu)LoadControl("~/mymenupath.ascx");
lbmsg.Text = adminmenu.selectedtab;
When you call LoadControl in your master page, you are actually creating a new instance of your user control, not accessing the one you have somewhere in your site.
When you declare the User Control in your page you should have given it an id. You could access the property with something like ((usercontrols.mainmenu)MyUserControlId).selectedtab
I found the solution by using Delegate, you can see in the link below.
http://webdeveloperpost.com/Articles/Return-value-from-user-control-in-ASP-NET-and-C-Sharp.aspx

Access property of parent page in user control

I have a hidden field on my default.aspx page. Within default.aspx page I have a user control which has a label on it. I need the label to display the value on the hidden field. How can I go about this?
Create a public property on the user control which exposes the label text:
public string LabelText
{
get { return this.label1.Text; }
set { this.label1.Text = value; }
}
Then set this from the page code-behind. So if the ASPX for your page has something like this in it:
<uc1:UserControl ID="userControl" runat="server" />
In the code-behind, you could do
this.userControl.LabelText = "something";
Doing it this way means that your user control doesn't have to know about the page that's using it. This helps the user control to be re-used on many different pages.

set validatorcontrol.setfocusonerror="true" for all validator controls in asp.net website

We are about to release beta version of our website. Lately we have seen that developers have not set setfocusonerror on any of the validaor controls used.We have to set this property.
Now, one solution is to open every page and put this property in place. I am looking for some othe way like some configuration in web.config or some other quick solution.
I have usercontrols and pages. Page derive from base page.Please suggest.
Loops through all the page controls in the Page_Load event on your base page and do it. In this example, pass the Page to SetValidationControls
protected void SetValidationControls(Control control)
{
foreach(Control ctrl in control.Controls)
{
if(ctrl is System.Web.UI.WebControls.RequiredFieldValidator)
{
RequiredFieldValidator req = (RequiredFieldValidator)ctrl;
req.SetFocusOnError = true;
}
else if (ctrl is System.Web.UI.WebControls.RegularExpressionValidator)
{
RegularExpressionValidator reg = (RegularExpressionValidator)ctrl;
reg.SetFocusOnError = true;
}
else if (ctrl.Controls.Count > 0)
SetValidationControls(ctrl);
}
}
And so on.
You can create a set of validators that derive from the one's supplied by ASP.NET and use those. This allows you to have more control over it and make application wide changes, for instance, by using the themes & skins file.
For instance, when using the RequiredFieldValidator, you can override it and add a new themable property, like this:
public class CustomRequiredFieldValidator : RequiredFieldValidator
{
[ToolboxItem(true), Themeable(true), Category("Appearance")]
public bool FocusOnError
{
get { return this.SetFocusOnError; }
set { this.SetFocusOnError = value; }
}
}
And in the skin file you can define a default instance of your CustomRequiredFieldValidator.
<myOwn:CustomRequiredFieldValidator runat="server" FocusOnError="True" />
Now all CustomRequiredFieldValidator instances in your web application will have their SetFocusOnError attribute set.

How to initialize a ASP.NET User Control With parameter?

For example, I have a user control(ascx) with a label inside,
I will use the the user control in my aspx page.
How can I pass a string value to the ascx page so that it can be display in the label of ascx page at the beginning?
Add this...
public string Whatever
{
get { return label.Text; }
set { label.Text = value; }
}
to your ascx control. Then from the page you are putting it in you can just set the text like... usercontrol.Whatever = "text to display";
or you can use the Whatever as a property on the aspx side of the page.
You can expose whatever controls you want access to in your user control by creating property for them.
In the past when I have had user controls that required certain data for setup I would create an Initialize method which would take in and setup whatever was needed.

Resources