Databases Reference
In-Depth Information
Updating Data Control When FieldValue Changes
Template's
FieldValue
property can also change because of something
outside
of the field
template, perhaps another custom field template. You could imagine a custom
ZipCode
field template that in response to the user entering a valid U.S. zip code could look up the
name of the city it represents and change the value displayed by the general-purpose
Text_Edit
field template for the
City
field.
The field template (
Text_Edit
) can detect when the
FieldValue
property changes by
overriding the
OnFieldValueChanged
method, as shown in Listing 10.18. Notice how
this overridden method sets the
Text
property of the
TextBox
control using the
FieldValueEditString
property of the template. As discussed in Chapter 3, “Field
Templates,” this property returns the
FieldValue
formatted appropriately for Edit mode.
This property is used in the template markup to provide the initial value for the
Text
property at the time of data binding, and the overridden
OnFieldValueChanged
method
needs to be consistent with this logic.
Taking Advantage of the Extended Field Templates
With the new version of the general-purpose
Text_Edit
field template, you can now
modify the custom
Region_Edit
field template shown back in Listing 10.15 so that it no
longer depends on the
Country
data control being a
TextBox
. In the next example, its
OnLoad
method was modified to initialize the
AutoPostBack
property of the template and
assign its
FieldValueChanged
event:
private UnleashedFieldTemplate countryFieldTemplate;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.countryFieldTemplate = this.FindOtherFieldTemplate(“Country”);
this.countryFieldTemplate.AutoPostBack = true;
this.countryFieldTemplate.FieldValueChanged +=
CountryFieldTemplate_FieldValueChanged;
}
The
FieldValueChanged
event handler, which is shown next, replaces the
TextChanged
event handler from the previous version of the
Region_Edit
field template, which had to
extract the current field value directly from the
TextBox
data control. Now that the
FieldValueEditString
property of the
Country
field template became available during
post-backs, this method uses it to update the list of regions in the drop-down list. Notice
that this is the same way the drop-down list is initially populated in the
OnDataBinding
method when the page is generated for the first time:
private void CountryFieldTemplate_FieldValueChanged(
object sender, EventArgs e)
{
string country = this.countryFieldTemplate.FieldValueEditString;
this.PopulateRegionList(country);
}