Login    
 
 
 
 
Text/HTML
  
You are here :: Blogs Saturday, May 19, 2012

Search
Note: This uses the internal blog search engine. The Google search engine is also available at the top of the page.
  
Disclaimer

Please review the site disclaimer before downloading or using content found on this site

  
Categories
  
DEVSHED Blog
As always, I welcome your comments!
Apr 8

Written by: Steve Gray
4/8/2011 12:08 PM  RssIcon

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
  1. <%@ Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="Validation.aspx.vb" Inherits="Grid_Validation" %>
  2.  
  3.  
  4. <%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
  5. <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
  6. </asp:Content>
  7.  
  8. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
  9.     <!-- content start -->
  10.     <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
  11.         <AjaxSettings>
  12.             <telerik:AjaxSetting AjaxControlID="ValidationSummary1">
  13.                 <UpdatedControls>
  14.                     <telerik:AjaxUpdatedControl ControlID="ValidationSummary1" />
  15.                 </UpdatedControls>
  16.             </telerik:AjaxSetting>
  17.             <telerik:AjaxSetting AjaxControlID="RadGrid1">
  18.                 <UpdatedControls>
  19.                     <telerik:AjaxUpdatedControl ControlID="RadGrid1" />
  20.                 </UpdatedControls>
  21.             </telerik:AjaxSetting>
  22.         </AjaxSettings>
  23.     </telerik:RadAjaxManager>
  24.  
  25.     <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
  26.     <script type="text/javascript">
  27.             function clientUnitPriceValidation(source, arguments) {
  28.                 var currentCell = source.parentNode;
  29.                 var currentRow = currentCell.parentNode
  30.  
  31.                 //get a reference to the calling validator control
  32.                 var CustomValidator1 = source.id;
  33.  
  34.                 //order
  35.                 var order
  36.                 //order = currentRow.KeyValues("order");
  37.  
  38.                 //get the value of the GridBoundColumn 'salesperson'
  39.                 var salesperson;
  40.                 salesperson = $telerik.findElement(currentRow, CustomValidator1.replace('CustomValidator1', 'ID_salesperson')).value
  41.  
  42.                 //get the value of the template column 'quantity'
  43.                 var quantity;
  44.                 quantity = document.getElementById(CustomValidator1.replace('CustomValidator1', 'txtQuantity')).value;
  45.                 quantity = $telerik.findElement(currentRow, "txtQuantity").value;
  46.  
  47.                 //get the value of the field being validated
  48.                 var unitPrice;
  49.                 unitPrice = document.getElementById(CustomValidator1.replace('CustomValidator1', 'txtunitPrice')).value;
  50.                 unitPrice = $telerik.findElement(currentRow, "txtunitPrice").value;
  51.  
  52.                 //get the value of the hidden 'minPrice' field
  53.                 var minPrice
  54.                 minPrice = $telerik.findElement(currentRow, CustomValidator1.replace('CustomValidator1', 'ID_minPrice')).value
  55.  
  56.                 //business logic here to determine
  57.                 //arguments.IsValid = false
  58.                 //or
  59.                 //arguments.IsValid = true
  60.  
  61.             }
  62.     </script>
  63.  
  64.     </telerik:RadCodeBlock>
  65.     <br />
  66.     <h3>Client Side and Server Side validation</h3>
  67.     The grid has a dispaly=false field called 'minPrice'
  68.     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 />
  69.  
  70.     The Salesperson field has a dynamically generated 'required field' validator which operates client side.
  71.     <br />
  72.     The UnitPrice field has a client side and a server side validator <br />
  73.     The server side validator only kicks in after the client validation passes.
  74.     <br />
  75.     <br />
  76.     This grid will only 'save' if the unitPrice is greater than 2, otherwise validation fails
  77.     <br />
  78.     <a href="http://www.telerik.com/help/aspnet/grid/grdvalidation.html" target="_blank">
  79.         Telerik Documentation</a>
  80.     <br />
  81.     <br />
  82.     <asp:ValidationSummary ID="ValidationSummary1" runat="server"  Enabled="true" ForeColor="Red" HeaderText="Errors:"
  83.         ShowSummary="true" DisplayMode="List" />
  84.     <telerik:RadGrid ID="RadGrid1" ClientInstanceName="RadGrid1" runat="server" AutoGenerateColumns="false" CssClass="grid"
  85.         Skin="Web20">
  86.         <MasterTableView DataKeyNames="order, minPrice" EditMode="InPlace" CommandItemDisplay="Top">
  87.             <CommandItemTemplate>
  88.                 <asp:LinkButton ID="btnEditSelected" runat="server"  CommandName="EditSelected" Visible='true' Width="80" >
  89.                     <asp:Image runat="server" Style="border: 0px; vertical-align: middle;" ID="imgEditButton" ImageUrl="~/images/Edit.gif" />Edit All
  90.                 </asp:LinkButton>
  91.                 <asp:LinkButton ID="btnUpdate"  runat="server" CommandName="UpdateAll" Visible='true' >
  92.                     <asp:Image runat="server" Style="border: 0px; vertical-align: middle;" ID="Image1" ImageUrl="~/images/Savehs.png" />Update All
  93.                 </asp:LinkButton>
  94.             </CommandItemTemplate>
  95.             <Columns>
  96.                 <telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn">
  97.                     <ItemStyle CssClass="MyImageButton" />
  98.                 </telerik:GridEditCommandColumn>
  99.                 
  100.                 <telerik:GridBoundColumn DataField="order" UniqueName="order"  HeaderText="Order" ReadOnly="true"></telerik:GridBoundColumn>
  101.                 
  102.                 <telerik:GridBoundColumn DataField="salesperson" HeaderText="SalesPerson" UniqueName="salesperson"></telerik:GridBoundColumn>
  103.  
  104.                 <telerik:GridTemplateColumn HeaderText="quantity" UniqueName="quantity">
  105.                     <ItemTemplate>
  106.                         <asp:Label runat="server" ID="lblQuantity" Text='<%# Eval("quantity", "{0:N2}") %>'></asp:Label>
  107.                     </ItemTemplate>
  108.                     <EditItemTemplate>
  109.                         <telerik:RadNumericTextBox runat="server" ID="txtQuantity" Width="40px" DbValue='<%# Bind("quantity") %>'>
  110.                         </telerik:RadNumericTextBox>
  111.                     </EditItemTemplate>
  112.                 </telerik:GridTemplateColumn>
  113.  
  114.                 <telerik:GridTemplateColumn HeaderText="unitPrice" UniqueName="unitPrice">
  115.                     <ItemTemplate>
  116.                         <asp:Label runat="server" ID="lblunitPrice" Text='<%# Eval("unitPrice", "{0:N2}") %>'></asp:Label>
  117.                     </ItemTemplate>
  118.                     <EditItemTemplate>
  119.                         <telerik:RadNumericTextBox runat="server" ID="txtunitPrice" Width="40px" DbValue='<%# Bind("unitPrice") %>'>
  120.                         </telerik:RadNumericTextBox>
  121.                         <asp:CustomValidator ID="CustomValidator1" ControlToValidate="txtunitPrice" ClientValidationFunction="clientUnitPriceValidation"
  122.                             OnServerValidate="ServerUnitPriceValidation" Display="Dynamic" ErrorMessage="Not an even number!"
  123.                             Text="Unit Price Must Be => 2" ForeColor="green" Font-Name="verdana" Font-Size="10pt"
  124.                             runat="server" />
  125.                     </EditItemTemplate>
  126.                 </telerik:GridTemplateColumn>
  127.  
  128.                 <telerik:GridBoundColumn DataField="minPrice" UniqueName="minPrice" Display="false"></telerik:GridBoundColumn>
  129.             </Columns>
  130.         </MasterTableView>
  131.     </telerik:RadGrid>
  132. </asp:Content>

and the code behind:

Code Snippet
  1. Imports Telerik.Web.UI
  2. Imports System.Data
  3.  
  4. Partial Class Grid_Validation
  5.     Inherits System.Web.UI.Page
  6.  
  7.     Dim oDT As DataTable
  8.  
  9.     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  10.         'store the data source in the session so it can be edited and updated
  11.         If Session("oDT") Is Nothing Then
  12.             Session("oDT") = GetDataTable()
  13.             oDT = GetDataTable()
  14.         Else
  15.             oDT = Session("oDT")
  16.         End If
  17.  
  18.     End Sub
  19.  
  20.     Sub bindGrid()
  21.         'setup and bind the grid
  22.         Me.RadGrid1.Width = "600"
  23.         Me.RadGrid1.AllowMultiRowEdit = True
  24.         Me.RadGrid1.DataSource = oDT
  25.     End Sub
  26.  
  27.  
  28.     Protected Sub RadGrid1_ItemCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.ItemCommand
  29.         Dim strOrder As String
  30.  
  31.         Select Case e.CommandName
  32.  
  33.             Case "EditSelected"
  34.                 'the user has clicked the 'Edit' button in the grid header.
  35.                 'set all items to edit mode
  36.                 For Each item As GridItem In RadGrid1.MasterTableView.Items
  37.                     If TypeOf item Is GridEditableItem Then
  38.                         Dim editableItem As GridEditableItem = CType(item, GridDataItem)
  39.                         editableItem.Edit = True
  40.                     End If
  41.  
  42.                 Next
  43.                 RadGrid1.Rebind()
  44.             Case "Update"
  45.                 'the user has clicked the 'update' button on a row
  46.                 'if the data passes validation...
  47.                 If Page.IsValid Then
  48.                     'update the row
  49.  
  50.                     'get a reference to the row
  51.                     Dim item As GridEditableItem = DirectCast(e.Item, GridEditableItem)
  52.  
  53.                     'The GridTableView will fill the values from all editable columns in the hash
  54.                     'get the New Values
  55.                     Dim newValues As Hashtable = New Hashtable
  56.                     e.Item.OwnerTableView.ExtractValuesFromItem(newValues, e.Item)
  57.  
  58.                     strOrder = CType(item.FindControl("ID_order"), TextBox).Text
  59.                     Dim dblQuantity As Double = newValues("quantity")
  60.                     Dim dblunitPrice As Double = newValues("unitPrice")
  61.                     Dim strSalesperson As String = newValues("salesperson")
  62.                     updateDataTable(strOrder, strSalesperson, dblQuantity, dblunitPrice)
  63.  
  64.                     'turn off edit mode
  65.                     item.Edit = False
  66.  
  67.                     'rebind the grid
  68.                     RadGrid1.Rebind()
  69.                 End If
  70.  
  71.             Case "UpdateAll"
  72.                 'the user has clicked the 'update' button in the header
  73.                 'if the data passes validation...
  74.                 If Page.IsValid Then
  75.                     'update the rows
  76.  
  77.                     'for each row in the grid
  78.                     For Each editedItem As GridEditableItem In RadGrid1.EditItems
  79.  
  80.                         'code to update the dataset here
  81.                         Dim newValues As Hashtable = New Hashtable
  82.  
  83.                         'The GridTableView will fill the values from all editable columns in the hash
  84.                         e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem)
  85.  
  86.                         strOrder = CType(editedItem.FindControl("ID_order"), TextBox).Text
  87.                         Dim dblQuantity As Double = newValues("quantity")
  88.                         Dim dblunitPrice As Double = newValues("unitPrice")
  89.                         Dim strSalesperson As String = newValues("salesperson")
  90.                         updateDataTable(strOrder, strSalesperson, dblQuantity, dblunitPrice)
  91.  
  92.                         'turn off edit mode
  93.                         editedItem.Edit = False
  94.  
  95.                         'If (TypeOf editedItem Is GridEditableItem AndAlso editedItem.IsInEditMode) Then
  96.                         'End If
  97.                     Next
  98.  
  99.                     'rebind the grid
  100.                     RadGrid1.Rebind()
  101.                 End If
  102.  
  103.         End Select
  104.  
  105.  
  106.     End Sub
  107.     Sub ServerUnitPriceValidation(ByVal source As Object, ByVal arguments As ServerValidateEventArgs)
  108.         Dim salesperson As String
  109.         Dim order As String
  110.         Dim minPrice As Double
  111.         Dim unitPrice As Double
  112.         Dim quantity As Double
  113.  
  114.         'get the value of the field being validated
  115.         Dim dblunitPrice As Double = Double.Parse(arguments.Value)
  116.  
  117.         Dim editItems As GridItemCollection = Me.RadGrid1.EditItems
  118.  
  119.         For Each editItem As GridEditableItem In editItems
  120.             'order
  121.             order = editItem.GetDataKeyValue("order")
  122.             order = CType(editItem.Controls(3).Controls(0), TextBox).Text
  123.             order = CType(editItem.FindControl("ID_order"), TextBox).Text
  124.  
  125.             'salesperson
  126.             salesperson = CType(editItem.Controls(4).Controls(0), TextBox).Text
  127.             'this id was assigned in the ItemCreated event
  128.             salesperson = CType(editItem.FindControl("ID_salesperson"), TextBox).Text
  129.             salesperson = editItem.SavedOldValues("salesperson")
  130.  
  131.             'quantity
  132.             quantity = CType(editItem.Controls(5).Controls(1), RadNumericTextBox).Text
  133.             quantity = CType(editItem.FindControl("txtQuantity"), RadNumericTextBox).Text
  134.             quantity = editItem.SavedOldValues("quantity")
  135.  
  136.             'two ways to get the UnitPrice text box value
  137.             unitPrice = CType(editItem.Controls(6).Controls(1), RadNumericTextBox).Text
  138.             unitPrice = CType(editItem.FindControl("txtunitprice"), RadNumericTextBox).Text
  139.             unitPrice = editItem.SavedOldValues("unitPrice")
  140.  
  141.             'minPrice
  142.             minPrice = editItem.GetDataKeyValue("minPrice")
  143.             minPrice = CType(editItem.Controls(7).Controls(0), TextBox).Text
  144.             minPrice = CType(editItem.FindControl("ID_minPrice"), TextBox).Text
  145.             minPrice = editItem.SavedOldValues("minPrice")
  146.  
  147.             'business logic here to either say
  148.             arguments.IsValid = True
  149.             '    or
  150.             ' arguments.IsValid = False
  151.  
  152.         Next
  153.  
  154.     End Sub
  155.  
  156.     Function GetDataTable() As DataTable
  157.         'create and return a datatable
  158.  
  159.         Dim oDT As New DataTable
  160.         Dim oKeys(0) As DataColumn
  161.         'create a data table to use as our input source
  162.  
  163.         'create columns
  164.         Dim oCol As DataColumn = New DataColumn("order", System.Type.GetType("System.String"))
  165.         oDT.Columns.Add(oCol)
  166.         oKeys(0) = oCol
  167.         oDT.Columns.Add(New DataColumn("salesperson", System.Type.GetType("System.String")))
  168.         oDT.Columns.Add(New DataColumn("quantity", System.Type.GetType("System.Double")))
  169.         oDT.Columns.Add(New DataColumn("unitPrice", System.Type.GetType("System.Double")))
  170.         oDT.Columns.Add(New DataColumn("minPrice", System.Type.GetType("System.Double")))
  171.         oDT.PrimaryKey = oKeys
  172.  
  173.         'create the rows
  174.         oDT.Rows.Add("ORD00101", "salesman1", 1, 1.11, 0.91)
  175.         oDT.Rows.Add("ORD00102", "salesman2", 2, 2.22, 0.92)
  176.         oDT.Rows.Add("ORD00103", "salesman3", 3, 3.33, 0.93)
  177.         oDT.Rows.Add("ORD00104", "salesman4", 4, 4.44, 0.94)
  178.  
  179.         Return oDT
  180.  
  181.     End Function
  182.  
  183.     Sub updateDataTable(ByVal strOrder As String, ByVal strSalesperson As String, ByVal dblQuantity As Double, ByVal dblunitPrice As Double)
  184.         'update the data table
  185.  
  186.         Dim oRow As DataRow
  187.  
  188.         '"order" is our primary key. Search the primary key for strOrder
  189.         oRow = oDT.Rows.Find(strOrder)
  190.  
  191.         'in the row found, set the unitPrice column
  192.         oRow("quantity") = dblQuantity
  193.         oRow("unitPrice") = dblunitPrice
  194.         oRow("salesperson") = strSalesperson
  195.  
  196.         'save
  197.         oDT.AcceptChanges()
  198.  
  199.     End Sub
  200.  
  201.     Protected Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid1.ItemCreated
  202.         'add a validator for the 'salesperson' control dynamicaly
  203.         Dim editor As GridTextBoxColumnEditor
  204.  
  205.         If (TypeOf e.Item Is GridEditableItem AndAlso e.Item.IsInEditMode) Then
  206.  
  207.             Dim item As GridEditableItem = CType(e.Item, GridEditableItem)
  208.             editor = New GridTextBoxColumnEditor
  209.             editor = CType(item.EditManager.GetColumnEditor("salesperson"), GridTextBoxColumnEditor)
  210.             Dim cell As TableCell = CType(editor.TextBoxControl.Parent, TableCell)
  211.             Dim validator As RequiredFieldValidator = New RequiredFieldValidator
  212.  
  213.             editor.TextBoxControl.ID = "ID_salesperson"
  214.             validator.ControlToValidate = editor.TextBoxControl.ID
  215.             validator.ErrorMessage = "Invalid Salesperson"
  216.             validator.Text = "*"
  217.             validator.Display = ValidatorDisplay.Dynamic
  218.             validator.ForeColor = Drawing.Color.Red
  219.             cell.Controls.Add(validator)
  220.  
  221.             'assign an ID to the minPrice column
  222.             editor = New GridTextBoxColumnEditor
  223.             editor = CType(item.EditManager.GetColumnEditor("minPrice"), GridTextBoxColumnEditor)
  224.             editor.TextBoxControl.ID = "ID_minPrice"
  225.  
  226.             'assign an ID to the order column
  227.             editor = New GridTextBoxColumnEditor
  228.             editor = CType(item.EditManager.GetColumnEditor("order"), GridTextBoxColumnEditor)
  229.             editor.TextBoxControl.ID = "ID_order"
  230.         End If
  231.  
  232.     End Sub
  233.  
  234.     Protected Sub RadGrid1_NeedDataSource(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles RadGrid1.NeedDataSource
  235.         bindGrid()
  236.     End Sub
  237. End Class

Tags:
Categories:
As always, I welcome your comments!
  
 
 
Home | Products | Blogs | Contact Us | Links | God's Plan
Privacy Statement | Terms Of Use
 
Copyright 2011 by Devshed.us