|
 |
| Note:
This uses the internal blog search engine. The Google search engine is also available at the top of the page. |
|
|
 |
|
|
|
|
 |
Please review the site disclaimer before downloading or using content found on this site
|
|
|
 |
|
|
|
|
|
 |
As always, I welcome your comments!
Apr
8
Written by:
Steve Gray
4/8/2011 12:08 PM
This is a complete web page, if you copy it into an ASP.NET application it will run, data source and all. The aim here is to completely document how client and server validation works so that future projects will go much faster. There are several ‘gotchas’, it took me a week of hard work to put this all together. Client and Server validation is slightly different, and there are several types of fields: DataKeyNames, GridBoundColumns and TemplateColumns. To validate you sometimes need access to one or more of these field types to make a business decision. The example code covers validating one line at a time, and also ‘mass updating’ a grid that has all the lines in edit mode… quite a trick. The last thing that I had to figure out was the getting the validation summary control to update when using server validation, the answer was to put the control n the ‘Ajax Updated Controls’ area. You can view the working grid here There are two pieces of code, the web page and the code behind. First, the web page: Code Snippet - <%@ Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="Validation.aspx.vb" Inherits="Grid_Validation" %>
-
-
- <%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
- <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
- </asp:Content>
-
- <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
- <!-- content start -->
- <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
- <AjaxSettings>
- <telerik:AjaxSetting AjaxControlID="ValidationSummary1">
- <UpdatedControls>
- <telerik:AjaxUpdatedControl ControlID="ValidationSummary1" />
- </UpdatedControls>
- </telerik:AjaxSetting>
- <telerik:AjaxSetting AjaxControlID="RadGrid1">
- <UpdatedControls>
- <telerik:AjaxUpdatedControl ControlID="RadGrid1" />
- </UpdatedControls>
- </telerik:AjaxSetting>
- </AjaxSettings>
- </telerik:RadAjaxManager>
-
- <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
- <script type="text/javascript">
- function clientUnitPriceValidation(source, arguments) {
- var currentCell = source.parentNode;
- var currentRow = currentCell.parentNode
-
- //get a reference to the calling validator control
- var CustomValidator1 = source.id;
-
- //order
- var order
- //order = currentRow.KeyValues("order");
-
- //get the value of the GridBoundColumn 'salesperson'
- var salesperson;
- salesperson = $telerik.findElement(currentRow, CustomValidator1.replace('CustomValidator1', 'ID_salesperson')).value
-
- //get the value of the template column 'quantity'
- var quantity;
- quantity = document.getElementById(CustomValidator1.replace('CustomValidator1', 'txtQuantity')).value;
- quantity = $telerik.findElement(currentRow, "txtQuantity").value;
-
- //get the value of the field being validated
- var unitPrice;
- unitPrice = document.getElementById(CustomValidator1.replace('CustomValidator1', 'txtunitPrice')).value;
- unitPrice = $telerik.findElement(currentRow, "txtunitPrice").value;
-
- //get the value of the hidden 'minPrice' field
- var minPrice
- minPrice = $telerik.findElement(currentRow, CustomValidator1.replace('CustomValidator1', 'ID_minPrice')).value
-
- //business logic here to determine
- //arguments.IsValid = false
- //or
- //arguments.IsValid = true
-
- }
- </script>
-
- </telerik:RadCodeBlock>
- <br />
- <h3>Client Side and Server Side validation</h3>
- The grid has a dispaly=false field called 'minPrice'
- This demo shows how to retrieve client side GridBoundColumn fields, TemplateColumn fields, and Display=False fields, as well as the same types of fields server side<br /><br />
-
- The Salesperson field has a dynamically generated 'required field' validator which operates client side.
- <br />
- The UnitPrice field has a client side and a server side validator <br />
- The server side validator only kicks in after the client validation passes.
- <br />
- <br />
- This grid will only 'save' if the unitPrice is greater than 2, otherwise validation fails
- <br />
- <a href="http://www.telerik.com/help/aspnet/grid/grdvalidation.html" target="_blank">
- Telerik Documentation</a>
- <br />
- <br />
- <asp:ValidationSummary ID="ValidationSummary1" runat="server" Enabled="true" ForeColor="Red" HeaderText="Errors:"
- ShowSummary="true" DisplayMode="List" />
- <telerik:RadGrid ID="RadGrid1" ClientInstanceName="RadGrid1" runat="server" AutoGenerateColumns="false" CssClass="grid"
- Skin="Web20">
- <MasterTableView DataKeyNames="order, minPrice" EditMode="InPlace" CommandItemDisplay="Top">
- <CommandItemTemplate>
- <asp:LinkButton ID="btnEditSelected" runat="server" CommandName="EditSelected" Visible='true' Width="80" >
- <asp:Image runat="server" Style="border: 0px; vertical-align: middle;" ID="imgEditButton" ImageUrl="~/images/Edit.gif" />Edit All
- </asp:LinkButton>
- <asp:LinkButton ID="btnUpdate" runat="server" CommandName="UpdateAll" Visible='true' >
- <asp:Image runat="server" Style="border: 0px; vertical-align: middle;" ID="Image1" ImageUrl="~/images/Savehs.png" />Update All
- </asp:LinkButton>
- </CommandItemTemplate>
- <Columns>
- <telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn">
- <ItemStyle CssClass="MyImageButton" />
- </telerik:GridEditCommandColumn>
-
- <telerik:GridBoundColumn DataField="order" UniqueName="order" HeaderText="Order" ReadOnly="true"></telerik:GridBoundColumn>
-
- <telerik:GridBoundColumn DataField="salesperson" HeaderText="SalesPerson" UniqueName="salesperson"></telerik:GridBoundColumn>
-
- <telerik:GridTemplateColumn HeaderText="quantity" UniqueName="quantity">
- <ItemTemplate>
- <asp:Label runat="server" ID="lblQuantity" Text='<%# Eval("quantity", "{0:N2}") %>'></asp:Label>
- </ItemTemplate>
- <EditItemTemplate>
- <telerik:RadNumericTextBox runat="server" ID="txtQuantity" Width="40px" DbValue='<%# Bind("quantity") %>'>
- </telerik:RadNumericTextBox>
- </EditItemTemplate>
- </telerik:GridTemplateColumn>
-
- <telerik:GridTemplateColumn HeaderText="unitPrice" UniqueName="unitPrice">
- <ItemTemplate>
- <asp:Label runat="server" ID="lblunitPrice" Text='<%# Eval("unitPrice", "{0:N2}") %>'></asp:Label>
- </ItemTemplate>
- <EditItemTemplate>
- <telerik:RadNumericTextBox runat="server" ID="txtunitPrice" Width="40px" DbValue='<%# Bind("unitPrice") %>'>
- </telerik:RadNumericTextBox>
- <asp:CustomValidator ID="CustomValidator1" ControlToValidate="txtunitPrice" ClientValidationFunction="clientUnitPriceValidation"
- OnServerValidate="ServerUnitPriceValidation" Display="Dynamic" ErrorMessage="Not an even number!"
- Text="Unit Price Must Be => 2" ForeColor="green" Font-Name="verdana" Font-Size="10pt"
- runat="server" />
- </EditItemTemplate>
- </telerik:GridTemplateColumn>
-
- <telerik:GridBoundColumn DataField="minPrice" UniqueName="minPrice" Display="false"></telerik:GridBoundColumn>
- </Columns>
- </MasterTableView>
- </telerik:RadGrid>
- </asp:Content>
and the code behind: Code Snippet - Imports Telerik.Web.UI
- Imports System.Data
-
- Partial Class Grid_Validation
- Inherits System.Web.UI.Page
-
- Dim oDT As DataTable
-
- Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
- 'store the data source in the session so it can be edited and updated
- If Session("oDT") Is Nothing Then
- Session("oDT") = GetDataTable()
- oDT = GetDataTable()
- Else
- oDT = Session("oDT")
- End If
-
- End Sub
-
- Sub bindGrid()
- 'setup and bind the grid
- Me.RadGrid1.Width = "600"
- Me.RadGrid1.AllowMultiRowEdit = True
- Me.RadGrid1.DataSource = oDT
- End Sub
-
-
- Protected Sub RadGrid1_ItemCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.ItemCommand
- Dim strOrder As String
-
- Select Case e.CommandName
-
- Case "EditSelected"
- 'the user has clicked the 'Edit' button in the grid header.
- 'set all items to edit mode
- For Each item As GridItem In RadGrid1.MasterTableView.Items
- If TypeOf item Is GridEditableItem Then
- Dim editableItem As GridEditableItem = CType(item, GridDataItem)
- editableItem.Edit = True
- End If
-
- Next
- RadGrid1.Rebind()
- Case "Update"
- 'the user has clicked the 'update' button on a row
- 'if the data passes validation...
- If Page.IsValid Then
- 'update the row
-
- 'get a reference to the row
- Dim item As GridEditableItem = DirectCast(e.Item, GridEditableItem)
-
- 'The GridTableView will fill the values from all editable columns in the hash
- 'get the New Values
- Dim newValues As Hashtable = New Hashtable
- e.Item.OwnerTableView.ExtractValuesFromItem(newValues, e.Item)
-
- strOrder = CType(item.FindControl("ID_order"), TextBox).Text
- Dim dblQuantity As Double = newValues("quantity")
- Dim dblunitPrice As Double = newValues("unitPrice")
- Dim strSalesperson As String = newValues("salesperson")
- updateDataTable(strOrder, strSalesperson, dblQuantity, dblunitPrice)
-
- 'turn off edit mode
- item.Edit = False
-
- 'rebind the grid
- RadGrid1.Rebind()
- End If
-
- Case "UpdateAll"
- 'the user has clicked the 'update' button in the header
- 'if the data passes validation...
- If Page.IsValid Then
- 'update the rows
-
- 'for each row in the grid
- For Each editedItem As GridEditableItem In RadGrid1.EditItems
-
- 'code to update the dataset here
- Dim newValues As Hashtable = New Hashtable
-
- 'The GridTableView will fill the values from all editable columns in the hash
- e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem)
-
- strOrder = CType(editedItem.FindControl("ID_order"), TextBox).Text
- Dim dblQuantity As Double = newValues("quantity")
- Dim dblunitPrice As Double = newValues("unitPrice")
- Dim strSalesperson As String = newValues("salesperson")
- updateDataTable(strOrder, strSalesperson, dblQuantity, dblunitPrice)
-
- 'turn off edit mode
- editedItem.Edit = False
-
- 'If (TypeOf editedItem Is GridEditableItem AndAlso editedItem.IsInEditMode) Then
- 'End If
- Next
-
- 'rebind the grid
- RadGrid1.Rebind()
- End If
-
- End Select
-
-
- End Sub
- Sub ServerUnitPriceValidation(ByVal source As Object, ByVal arguments As ServerValidateEventArgs)
- Dim salesperson As String
- Dim order As String
- Dim minPrice As Double
- Dim unitPrice As Double
- Dim quantity As Double
-
- 'get the value of the field being validated
- Dim dblunitPrice As Double = Double.Parse(arguments.Value)
-
- Dim editItems As GridItemCollection = Me.RadGrid1.EditItems
-
- For Each editItem As GridEditableItem In editItems
- 'order
- order = editItem.GetDataKeyValue("order")
- order = CType(editItem.Controls(3).Controls(0), TextBox).Text
- order = CType(editItem.FindControl("ID_order"), TextBox).Text
-
- 'salesperson
- salesperson = CType(editItem.Controls(4).Controls(0), TextBox).Text
- 'this id was assigned in the ItemCreated event
- salesperson = CType(editItem.FindControl("ID_salesperson"), TextBox).Text
- salesperson = editItem.SavedOldValues("salesperson")
-
- 'quantity
- quantity = CType(editItem.Controls(5).Controls(1), RadNumericTextBox).Text
- quantity = CType(editItem.FindControl("txtQuantity"), RadNumericTextBox).Text
- quantity = editItem.SavedOldValues("quantity")
-
- 'two ways to get the UnitPrice text box value
- unitPrice = CType(editItem.Controls(6).Controls(1), RadNumericTextBox).Text
- unitPrice = CType(editItem.FindControl("txtunitprice"), RadNumericTextBox).Text
- unitPrice = editItem.SavedOldValues("unitPrice")
-
- 'minPrice
- minPrice = editItem.GetDataKeyValue("minPrice")
- minPrice = CType(editItem.Controls(7).Controls(0), TextBox).Text
- minPrice = CType(editItem.FindControl("ID_minPrice"), TextBox).Text
- minPrice = editItem.SavedOldValues("minPrice")
-
- 'business logic here to either say
- arguments.IsValid = True
- ' or
- ' arguments.IsValid = False
-
- Next
-
- End Sub
-
- Function GetDataTable() As DataTable
- 'create and return a datatable
-
- Dim oDT As New DataTable
- Dim oKeys(0) As DataColumn
- 'create a data table to use as our input source
-
- 'create columns
- Dim oCol As DataColumn = New DataColumn("order", System.Type.GetType("System.String"))
- oDT.Columns.Add(oCol)
- oKeys(0) = oCol
- oDT.Columns.Add(New DataColumn("salesperson", System.Type.GetType("System.String")))
- oDT.Columns.Add(New DataColumn("quantity", System.Type.GetType("System.Double")))
- oDT.Columns.Add(New DataColumn("unitPrice", System.Type.GetType("System.Double")))
- oDT.Columns.Add(New DataColumn("minPrice", System.Type.GetType("System.Double")))
- oDT.PrimaryKey = oKeys
-
- 'create the rows
- oDT.Rows.Add("ORD00101", "salesman1", 1, 1.11, 0.91)
- oDT.Rows.Add("ORD00102", "salesman2", 2, 2.22, 0.92)
- oDT.Rows.Add("ORD00103", "salesman3", 3, 3.33, 0.93)
- oDT.Rows.Add("ORD00104", "salesman4", 4, 4.44, 0.94)
-
- Return oDT
-
- End Function
-
- Sub updateDataTable(ByVal strOrder As String, ByVal strSalesperson As String, ByVal dblQuantity As Double, ByVal dblunitPrice As Double)
- 'update the data table
-
- Dim oRow As DataRow
-
- '"order" is our primary key. Search the primary key for strOrder
- oRow = oDT.Rows.Find(strOrder)
-
- 'in the row found, set the unitPrice column
- oRow("quantity") = dblQuantity
- oRow("unitPrice") = dblunitPrice
- oRow("salesperson") = strSalesperson
-
- 'save
- oDT.AcceptChanges()
-
- End Sub
-
- Protected Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid1.ItemCreated
- 'add a validator for the 'salesperson' control dynamicaly
- Dim editor As GridTextBoxColumnEditor
-
- If (TypeOf e.Item Is GridEditableItem AndAlso e.Item.IsInEditMode) Then
-
- Dim item As GridEditableItem = CType(e.Item, GridEditableItem)
- editor = New GridTextBoxColumnEditor
- editor = CType(item.EditManager.GetColumnEditor("salesperson"), GridTextBoxColumnEditor)
- Dim cell As TableCell = CType(editor.TextBoxControl.Parent, TableCell)
- Dim validator As RequiredFieldValidator = New RequiredFieldValidator
-
- editor.TextBoxControl.ID = "ID_salesperson"
- validator.ControlToValidate = editor.TextBoxControl.ID
- validator.ErrorMessage = "Invalid Salesperson"
- validator.Text = "*"
- validator.Display = ValidatorDisplay.Dynamic
- validator.ForeColor = Drawing.Color.Red
- cell.Controls.Add(validator)
-
- 'assign an ID to the minPrice column
- editor = New GridTextBoxColumnEditor
- editor = CType(item.EditManager.GetColumnEditor("minPrice"), GridTextBoxColumnEditor)
- editor.TextBoxControl.ID = "ID_minPrice"
-
- 'assign an ID to the order column
- editor = New GridTextBoxColumnEditor
- editor = CType(item.EditManager.GetColumnEditor("order"), GridTextBoxColumnEditor)
- editor.TextBoxControl.ID = "ID_order"
- End If
-
- End Sub
-
- Protected Sub RadGrid1_NeedDataSource(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles RadGrid1.NeedDataSource
- bindGrid()
- End Sub
- End Class
As always, I welcome your comments! |
|
|
 |
|
|
|
|
|
|