HOWTO: Dynamically Add CustomValidator Control To Validation Summary

D

Dan Sikorsky

I'm getting the following message when I try to add a CustomValidator
control to the ValidationSummary to display an error message at runtime, and
displaying ex.message in AddValidationControl shows:

A control cannot modify its parents' control collections.





Here is the code:


Private Function Test() As Boolean



Dim x As Integer = 1

Try

x = x / 0

Catch ex As Exception

AddValidationControl(Me.Page, "frmMain", ex.Message)

End Try

Return True

End Function



In a separate Class Library, I have this function defined:
Public Shared Function AddValidationControl(ByRef PageControl As Page, ByRef
sFormName As String, _

ByRef sMessage As String) As Boolean

Dim valOther As System.Web.UI.WebControls.CustomValidator

Dim objForm As System.Web.UI.HtmlControls.HtmlForm

Dim blnReturn As Boolean

Try

If PageControl Is Nothing Then

Throw New Exception("PageControl was not set and has a value of
Nothing.")

Else

valOther = New System.Web.UI.WebControls.CustomValidator

valOther.ErrorMessage = sMessage

valOther.IsValid = False

valOther.Display = System.Web.UI.WebControls.ValidatorDisplay.None

objForm = PageControl.FindControl(sFormName)

objForm.Controls.Add(valOther) // exception occurs
on this line

blnReturn = True

End If

Catch ex As Exception

ex = Nothing

End Try

Return blnReturn

End Function





How can I resolve this error?



Thank you kindly,

Dan Sikorsky
 
D

Dan Sikorsky

One solution is to use a PlaceHolder control on the form and add the
CustomValidator control to the PlaceHolder control. The message will display
in the ValidationSummary just like an actual validation error message.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top