Naming Container – a new namespace is created that insures that the control Ids are unique within an application. Every server control has a NamingContainer property. You can use this property to locate a control within a page. A new instance of the Page class is the default NamingContainer for a newly requested page.
Because my DualValidator class has defined three new properties, there must be a way to locate the controls associated with these properties and acquire access to the values of these controls. The NamingContainer allows me to do so by searching its namespace using the FindControl() method.
Our requirement only required that we validate two dropdownlist objects, but with a few more lines of code, you can enhance this code to dynamically determine which type of control you need to cast your object into and access its values appropriately.
(partial code)
TextBox PrimaryControl = ((TextBox)NamingContainer.FindControl(primarycontrol));
DropDownList ControlValue1 = ((DropDownList)NamingContainer.FindControl(control1));
DropDownList ControlValue2 = ((DropDownList)NamingContainer.FindControl(control2));
FirstControl_Value = ControlValue1.SelectedItem.Value.ToString(); SecondControl_Value =
ControlValue2.SelectedItem.Value.ToString();
if (PrimaryControl.Text.Trim() != String.Empty)
{ if (FirstControl_Value.Trim() == String.Empty && SecondControl_Value.Trim() == String.Empty)
{ return false;
}
else if (FirstControl_Value.Trim() != String.Empty && SecondControl_Value.Trim() != String.Empty)
{ return false;
} |
Conclusion
This article showed us how to create a custom validator control that can be used in any .NET visual IDE designer. Every web developer needs to know how to provide his web application with validation capabilities. Although Microsoft has assisted us greatly in the area of validation, a professional developer cannot escape the need to develop his own custom validator. I hope this series of articles will assist you in acquiring this ability.
In the next article, King is going to show you how to give your validator the ability to validate using client-side validation.
Copyright: 2003 Keith A Wells and King S Wells Jr.