Listing 1 PoweredBoundField class declaration
using System;
using System.ComponentModel;
using System.Web.UI.WebControls;
namespace Powered01Cs
{
public class PoweredBoundField : BoundField
{
}
}
Imports System.Web.UI.WebControls
Public Class PoweredBoundField
Inherits BoundField
End Class
Listing 2 Some PoweredBoundField properties
/// <summary>
/// Enable/Disable Required Validation.
/// </summary>
[
Description("Required Validation"),
Category("Behavior"),
DefaultValue("false"),
]
public bool Required
{
get
{
object o = ViewState["EnableRequired"];
return (o != null ? (bool)o : false);
}
set
{
ViewState["EnableRequired"] = value;
}
}
/// <summary>
/// Required Validation Error Message.
/// </summary>
[
Description("Required Validation Error Message"),
Category("Behavior"),
DefaultValue(""),
]
public string RequiredErrorMessage
{
get
{
object o = ViewState["RequiredErrorMessage"];
return (o != null ? o.ToString() : "Required Field!!!");
}
set
{
ViewState["RequiredErrorMessage"] = value;
}
}
Public Property Required() As Boolean
Get
Dim o As Object = ViewState("EnableRequired")
If (IsNothing(o)) Then
Return False
Else
Return CBool(o)
End If
End Get
Set(ByVal value As Boolean)
ViewState("EnableRequired") = value
End Set
End Property
Public Property RequiredErrorMessage() As String
Get
Dim o As Object = ViewState("RequiredErrorMessage")
If (IsNothing(o)) Then
Return "Required Field!!!"
Else
Return CStr(o)
End If
End Get
Set(ByVal value As String)
ViewState("RequiredErrorMessage") = value
End Set
End Property
Listing 3 The InitializeCell method where we add the validator controls to the TextBox bound to the DataField
public override void InitializeCell(
DataControlFieldCell cell,
DataControlCellType cellType,
DataControlRowState rowState, int rowIndex)
{
base.InitializeCell(cell, cellType, rowState, rowIndex);
if (cellType == DataControlCellType.DataCell)
{
// If the row is in edit mode try to add Validators
if ((rowState & DataControlRowState.Edit) != 0 ||
(rowState & DataControlRowState.Insert) != 0)
{
try
{
// find the TextBox bound to the DataField
TextBox tb = (TextBox)cell.Controls[0];
tb.ID = DataField;
if (Required)
{
// add a RequiredFieldValidator and link it
// to the TextBox bound to the DataField
cell.Controls.Add(GetRequiredValidator(tb.ID,
RequiredErrorMessage));
}
if (RegularExpressionValidationString != "")
{
// add a RegularExpressionValidator and link it
// to the TextBox bound to the DataField
cell.Controls.Add(GetRegularExpressionValidator(
tb.ID, RegularExpressionValidationString,
RegularExpressionValidationErrorMessage));
}
}
catch { }
}
}
}
Public Overrides Sub InitializeCell(
ByVal cell As DataControlFieldCell, _
ByVal cellType As DataControlCellType, _
ByVal rowState As DataControlRowState, _
ByVal rowIndex As Integer)
MyBase.InitializeCell(cell, cellType, rowState, rowIndex)
If cellType = DataControlCellType.DataCell Then
' If the row is in edit mode try to add Validators
If (rowState And DataControlRowState.Edit) <> 0 _
OrElse (rowState And _
DataControlRowState.Insert) <> 0 Then
Try
' find the TextBox bound to the DataField
Dim tb As TextBox = CType(cell.Controls(0), TextBox)
tb.ID = DataField
If Required Then
' add a RequiredFieldValidator and link it
' to the TextBox bound to the DataField
cell.Controls.Add(GetRequiredValidator(tb.ID, _
RequiredErrorMessage))
End If
If RegularExpressionValidationString <> "" Then
' add a RegularExpressionValidator and link it
' to the TextBox bound to the DataField
cell.Controls.Add(GetRegularExpressionValidator( _
tb.ID, _
RegularExpressionValidationString, _
RegularExpressionValidationErrorMessage))
End If
Catch ex As Exception
End Try
End If
End If
End Sub
Listing 4 Private functions that build up validator controls
private RegularExpressionValidator
GetRegularExpressionValidator(
string inControlToValidate,
string inRegExprValidationString,
string inRegExprValidationErrorMessage)
{
RegularExpressionValidator rev =
new RegularExpressionValidator();
rev.ControlToValidate = inControlToValidate;
rev.ID = String.Concat("RegularExpressionValidatorOf",
inControlToValidate);
rev.Display = ValidatorDisplay.Dynamic;
rev.ValidationExpression = inRegExprValidationString;
rev.ErrorMessage = inRegExprValidationErrorMessage;
rev.Text = " (!)";
return rev;
}
Private Function GetRegularExpressionValidator( _
ByVal inControlToValidate As String, _
ByVal inRegExprValidationString As String, _
ByVal inRegExprValidationErrorMessage As String) _
As RegularExpressionValidator
Dim rev As New RegularExpressionValidator()
rev.ControlToValidate = inControlToValidate
rev.ID = "RegularExpressionValidatorOf" & _
CStr(inControlToValidate)
rev.Display = ValidatorDisplay.Dynamic
rev.ValidationExpression = inRegExprValidationString
rev.ErrorMessage = inRegExprValidationErrorMessage
rev.Text = " (!)"
Return rev
End Function
Listing 5 The Default.aspx page used to test PoweredBoundField controls
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="Powered01Cs"
Namespace="Powered01Cs"
TagPrefix="Powered01Cs" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Adding Validation Capabilities
to BoundControls</title>
<link rel="stylesheet" href="Powered.css" />
</head>
<body>
<form id="form1" runat="server">
<h1>Adding Validation Capabilities to BoundControls</h1>
<fieldset><legend>System Messages</legend>
<span id="Message" runat="server" style="FONT-SIZE: 8pt;
FONT-FAMILY: Verdana, Arial"> </span>
<asp:ValidationSummary ID="ValidationSummary1"
Runat="server" />
</fieldset>
<p></p>
<table>
<tr><td width="50%">
<asp:GridView ID="GridView1" runat="server"
DataSourceID="SqlDataSource1"
AutoGenerateColumns="false"
AutoGenerateEditButton="true" DataKeyNames="VendorId"
SelectedRowStyle-CssClass="GRDSelectedItem"
AlternatingRowStyle-CssClass="GRDAlternatingItem"
RowStyle-CssClass="GRDItem"
HeaderStyle-CssClass="GRDHeader"
BorderColor="black" BorderWidth="1"
GridLines="Both" AllowPaging="true" PageSize="20"
EnableSortingAndPagingCallbacks="true">
<Columns>
<asp:BoundField DataField="VendorId" HeaderText="Id"
ReadOnly="true" />
<Powered01Cs:PoweredBoundField
RegularExpressionValidationString="^[A-Z]{1,10}\d{4}$"
Required="true"
RequiredErrorMessage="Must Insert an Account Number"
DataField="AccountNumber"
HeaderText="Account Number" />
<Powered01Cs:PoweredBoundField Required="true"
RequiredErrorMessage="You Must Insert a Name"
DataField="Name" HeaderText="Name" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
SelectCommand="SELECT VendorId, AccountNumber, Name
FROM Purchasing.Vendor"
SelectCommandType="Text"
UpdateCommand="UPDATE Purchasing.Vendor SET
AccountNumber=@AccountNumber, Name=@Name WHERE
VendorId=@VendorId" UpdateCommandType="Text"
ConnectionString=
"<%$ ConnectionStrings:DBConnectionString %>"
OldValuesParameterFormatString="{0}" >
</asp:SqlDataSource>
</td>
<td valign="top" align="center" width="50%">
<img src="Powered01.gif" /></td>
</tr>
</table>
</form>
</body>
</html>