Fun with regular expressions: Adding validators to a DetailsView

For a recent prototype, we needed to add required-field validators to a bunch of fields in asp.net DetailsView controls.

We had to convert each BoundField to a TemplateField and add a RequiredFieldValidator.

In other words, we needed to transform

<asp:BoundField DataField="Country" HeaderText="Country" HeaderStyle-CssClass="importantHeader" />

to

<asp:TemplateField HeaderText="Country" HeaderStyle-CssClass="importantHeader">

<ItemTemplate>

<%# Eval("Country") %></ItemTemplate>

<EditItemTemplate>

<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Country") %>'></asp:TextBox><asp:RequiredFieldValidator

runat="server" Display="Dynamic" ControlToValidate="TextBox3" Text="Required" /></EditItemTemplate>

</asp:TemplateField>

That would be a tedious task to do manually. Regular expressions to the rescue!

image

Find what:

\<asp\:BoundField DataField="{.#}" {HeaderText=".#"}{.#}/\>

Replace with:

<asp:TemplateField \2 \3><ItemTemplate><%# Eval("\1") %></ItemTemplate><EditItemTemplate><asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("\1") %>'></asp:TextBox><asp:RequiredFieldValidator runat=server Display=Dynamic ControlToValidate=TextBox1 Text="Required" /></EditItemTemplate></asp:TemplateField>

Since not every field was required, I used Find Next to walk through the page and find each required field, then used Replace.

The ID for the text box and the RequiredFieldValidator ControlToValidate needed to be manually changed when the DetailsView contains more than one required field, but this bit of manual work was easy compared to the work saved by the regular expression search and replace.


Feedback

No comments posted yet.


Post a comment





 

Please add 1 and 2 and type the answer here: