ASP.Net codebehind can't access component from page?
For some unknown reason I have 1 page which I cannot access by ID of any component.
Here are some details. The page uses asp: Content because the website uses MasterPage. Inside the asp: Content, this page has an asp: FormView with some data that I cannot access from CodeBehind.
Here is the page declaration:
Here is the code on the page that doesn't compile:
protected void FormView1_PreRender(object sender, EventArgs e)
{
DateBirthdayValidator.MaximumValue = DateTime.Now.Date.ToString("dd-MM-yy");
}
Here is the error:
Error 2 The name "DateBirthdayValidator" does not exist in the current context
I have a google search, I have an answer about using FindControl but it doesn't work. Any idea?
Edit1:
I can access the FormView1 component, but not the validator inside the EditItemTemplate. How can I access the control that is inside the EditTemplate?
Edit2:
If I try: FormView1.FindControl("DateBirthdayValidator")
it compiles but always returns null. So it still doesn't work, but at least I can access FormView1 ...
a source to share
protected void FormView1_PreRender(object sender, EventArgs e)
{
if(FormView1.CurrentMode == FormViewMode.Edit)
((RangeValidator)FormView1.FindControl("DateBirthdayValidator")).MaximumValue = DateTime.Now.Date.ToString("dd-MM-yy");
}
There is no control in the FormView that is created until it is in the desired mode. Since the DateBirhdayValidator was in edit mode, it must have validation in CodeBehind to be sure to find the control only when the state is in edit mode.
I found the solution here , see the post from Steven Cheng [MSFT].
a source to share
The problem is that the validator you provided as a form doesn't really exist at the page level. This is the template that you define for yours FormView
. The parent control can instantiate the template (zero, one, or more times, for example, think about each line in GridView
) and, as a consequence, create its controls). You should try to access it, for example:
// Replace RangeValidator with the actual validator type, if different.
var v = (RangeValidator)myFormView.Row.FindControl("DateBirthdayValidator");
v.MaximumValue = ...;
Note that in order to do this, your form view must be in the mode in which you declared your validator (you can check this with a property CurrentMode
), and you must have already called DataBind
to bind it to the data source (so that at least one row exists, and thus the template is instantiated).
a source to share
Do you have an DateBirthdayValidator
aspx declared on the page? Also check that Visual Studio creates the appropriate declaration DateBirthdayValidator
in the designer file for your page. It looks like it's most likely the designer file doesn't have a declaration for the control.
a source to share