CustomValidator in the EditItemTemplate of a DataGrid

  • Thread starter Thread starter Dave
  • Start date Start date
D

Dave

I have added a custom validator to the EditItemTemplate of a DataGrid as
follows:

<EditItemTemplate>
<asp:TextBox id=txtWorkDate CssClass="ResultsDim" runat="server"
Width="100%" Text='<%# DataBinder.Eval(Container,
"DataItem.WorkDate","{0:g}") %>' >
</asp:TextBox>
<asp:requiredfieldvalidator id="RfvWorkDate" runat="server"
ErrorMessage="Enter the Work Date" ControlToValidate="txtWorkDate"
EnableClientScript="false" Enabled="true" EnableViewState="true"
Visible="true">*</asp:requiredfieldvalidator>
<asp:CustomValidator id="WorkDateValidator" runat="server"
Display="Dynamic" ControlToValidate="txtWorkDate">*</asp:CustomValidator>
</EditItemTemplate>

-----------------------------------------------------------------------
I added the following to the codebehind page:

Protected WithEvents WorkDateValidator As
System.Web.UI.WebControls.CustomValidator
Protected WithEvents txtWorkDate As System.Web.UI.WebControls.TextBox

-----------------------------------------------------------------------
I do a Page.Validate in the Update command:

Public Sub DataGrid_Update(ByVal source As Object, ByVal e As
System.Web.UI.WebControls.DataGridCommandEventArgs)
Handles DGWork.UpdateCommand

Page.Validate()
If Page.IsValid() Then
...
...
...
End If
End Sub

-----------------------------------------------------------------------
I added the following code for the validator:

Private Sub WorkDateValidator_ServerValidate(ByVal source As
System.Object,
ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
Handles WorkDateValidator.ServerValidate

args.IsValid = False
End Sub

-----------------------------------------------------------------------
The required field validator works fine, but...

I find that if I run it in debug mode that WorkDateValidator_ServerValidate
is never called.

Any ideas?

Thanks,
Dave
 
Hi Dave,

You don't need to defineWorkDateValidator:

Protected WithEvents WorkDateValidator As
System.Web.UI.WebControls.CustomValidator

Just add following code before Page.Validate() in DataGrid_Update:

Dim MyValidator As CustomValidator
MyValidator = e.Item.FindControl("WorkDateValidator")
AddHandler MyValidator.ServerValidate, AddressOf
WorkDateValidator_ServerValidate

And the event will be fired.

Normally, we don't need to define the control in itemtemplate, just get
with FindControl

Luke
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
 
Back
Top