I’ve been using this for some time and thought I should post a small article on it.
Figure 1 – Highlighted fields
The idea is to give the user some prior knowledge the some field are required and these are have their backgrounds tinted yellow, so lets look at the code for this:
protected void Page_Load(object sender, EventArgs e) { TextBox1.ToolTip = Column.Description; SetUpValidator(RequiredFieldValidator1); SetUpValidator(RegularExpressionValidator1); SetUpValidator(DynamicValidator1); // add 'validationRequired' class to the TextBox if (Column.IsRequired) TextBox1.CssClass += " validationRequired"; }
Listing 1 – the highlighter code.
It’s the last if statement that does the work if the the column is required then the “validationRequired” class is added to the fields class.
/* required field class */ .validationRequired { background-color: #FFFEBD; }
Listing 2 – required field css class
Making ForeignKey Field Template have Required Validation
The next thing I like is to add validation the FK field templates so there is a select [type] as the first entry in the FK field if the field is required and validation is enabled.
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="droplist"> </asp:DropDownList> <asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1" CssClass="droplist" ControlToValidate="DropDownList1" Display="Dynamic" Enabled="false" /> <asp:DynamicValidator runat="server" ID="DynamicValidator1" CssClass="droplist" ControlToValidate="DropDownList1" Display="Dynamic" />
Listing 3 – ForeignKey_Edit.aspx
protected void Page_Load(object sender, EventArgs e) { if (DropDownList1.Items.Count == 0) { if (!Column.IsRequired || (Column.IsRequired && Mode == DataBoundControlMode.Insert)) { DropDownList1.Items.Add(new ListItem("[Not Set]", "")); } PopulateListControl(DropDownList1); } DropDownList1.ToolTip = Column.Description; SetUpValidator(RequiredFieldValidator1); SetUpValidator(DynamicValidator1); // add 'validationRequired' class to the TextBox if (Column.IsRequired) DropDownList1.CssClass += " validationRequired"; }
Listing 4 – ForeignKey_Edit.aspx.cs
In Listing 3 I have added the standard RequiredFieldValidator and DynamicValidator to the ForeignKet_Edit field template and in Listing 4 I have added the setup for both validators and also changed the if statement that adds the “[Not Set]” entry to the dropdown list; this is make sure the user picks a value when the column is required and it is in insert mode as opposed to just accepting the default value.
Like I said only a short article but neat
3 comments:
Excellent post and writing style. Bookmarked.
Thanx. .... Really helpful.
Super Bueno !! TNK
Post a Comment