Solved

javascript client side validation fails when gridview has more than one page,full demo included w Northwind

Posted on 2011-09-19
7
550 Views
Last Modified: 2012-05-12
Please find attached 3 files.
1. web.config with connectionstring set to Northwind on local pc
2. default.aspx
3. OrderDetails.aspx which is to be put in BaseLine folder

The problem:
javascript validates when the gridview on the only has 1x page
javascript does not validate when the gridview has > 1 page --> please help me with this, I cannot find why the validation fails
i have spent 3 days of my life on this.

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
	<connectionStrings>
		<add name="ConnectionString" connectionString="Integrated Security=SSPI;Initial Catalog=NorthWind;Data Source=localhost;" providerName="System.Data.SqlClient"/>
	</connectionStrings>
	<system.web>
			<authentication mode="Windows"/>
			<customErrors mode="Off"/>
		<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="en-ZA"/>
		<compilation debug="true"/></system.web>
	<location allowOverride="true" inheritInChildApplications="true">
		<appSettings>
			<add key="ConnectionString" value="Integrated Security=SSPI;Initial Catalog=NorthWind;Data Source=localhost;"/>
		</appSettings>
	</location>
</configuration>

Open in new window

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Response.Redirect("BaseLine/OrderDetails.aspx?OrderID=10249")
    End Sub
End Class




_______________

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" title="Untitled Page" %>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>

Open in new window

Imports System.Data
Partial Class BaseLine
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            If Not Page.IsPostBack Then
                Me.gv.DataBind()
                Dim SQLConnection As New SqlClient.SqlConnection
                Dim strSQLConn As String = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")
                SQLConnection.ConnectionString = strSQLConn
                SQLConnection.Open()

                Dim SQLCmd As New SqlClient.SqlCommand
                SQLCmd.Connection = SQLConnection
                SQLCmd.CommandType = CommandType.Text
                SQLCmd.CommandText = "select OrderID,ProductID,UnitPrice,Quantity,Discount from [Order Details] where OrderID='" & Request.QueryString("OrderID") & "'"
                Dim SQLTable As SqlClient.SqlDataReader
                SQLTable = SQLCmd.ExecuteReader
                SQLTable.Close()
            End If
        Catch ex As Exception
            Me.lblMessages.Visible = True
            Me.lblMessages.Text = ex.Message

        End Try
    End Sub

    Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
        If (Page.IsValid) Then
            Try
                If Me.lblMessages.Text <> "" Then
                    Exit Sub
                End If
            Catch ex As Exception
                Me.lblMessages.Visible = True

            End Try
        End If
    End Sub

    Private Sub RetrieveDetails()

        Dim SQLConnection As New SqlClient.SqlConnection
        Dim strSQLConn As String = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")
        SQLConnection.ConnectionString = strSQLConn
        SQLConnection.Open()

        Dim SQLCmd As New SqlClient.SqlCommand
        SQLCmd.Connection = SQLConnection
        SQLCmd.CommandType = CommandType.Text
        Dim SQLTable As SqlClient.SqlDataReader
        For Each row As GridViewRow In Me.gv.Rows
            SQLCmd.CommandText = "select OrderID,ProductID,UnitPrice,Quantity,Discount from [Order Details] where OrderID=" & Me.gv.DataKeys(row.RowIndex).Item("OrderID")
            SQLTable = SQLCmd.ExecuteReader
            While SQLTable.Read
                If Me.gv.DataKeys(row.RowIndex).Item("OrderID") = SQLTable.Item("OrderID") Then
                    CType(row.FindControl("txtUnitPrice"), TextBox).Text = SQLTable.Item("UnitPrice")
                End If
            End While
            SQLTable.Close()
        Next
        SQLTable.Close()
        SQLConnection.Close()

    End Sub

    Protected Sub gv_PageIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gv.PageIndexChanged
        Try
            Call RetrieveDetails()
        Catch ex As Exception
            Me.lblMessages.Text = ex.StackTrace
            Me.lblMessages.Visible = True
        End Try
    End Sub

End Class



_____________________________

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="OrderDetails.aspx.vb" Inherits="BaseLine" title="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<script language="javascript" type="text/javascript"> 
   function ValidateParameters()
        {
                         alert("!");                                                
 
                                                  
                         var grid = document.getElementById("<%= gv.ClientID %>");
                         
                         if (grid.rows.length > 0)
                         {
                            //loop starts from 1. rows[0] points to the header.
                            for (i=1; i<grid.rows.length; i++)
                            {
                                var cellCheckRequiredValue1 = grid.rows[i].cells[2].childNodes[1].value;
                                var cellCheckRequiredValue2 = grid.rows[i].cells[3].childNodes[0].value;
                                var cellCheckRequiredValue3 = grid.rows[i].cells[4].childNodes[0].value;
                         

 
                                if (cellCheckRequiredValue1 == "" || cellCheckRequiredValue2 == "" || cellCheckRequiredValue3 == ""  )
                                {
                                    alert("Please Enter All Supplied Values As Indicated In Red");
                                    return false;
                                }
                            }
                        }
            return true;
        }
        
        


 </script>

  <html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    &nbsp; &nbsp;
    <asp:Label ID="lblMessages" runat="server" Font-Size="10pt" ForeColor="Red" Style="z-index: 101;
        left: 13px; position: absolute; top: 145px" Visible="False" BackColor="Yellow"></asp:Label>
    &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
        &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
        &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
        &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
        &nbsp;
    <asp:GridView ID="gv" runat="server" AllowPaging="True" AllowSorting="True"
        AutoGenerateColumns="False" BackColor="White" BorderColor="White" BorderStyle="Ridge"
        BorderWidth="2px" CellPadding="3" CellSpacing="1" DataKeyNames="OrderID"
        DataSourceID="dsOrderDetails" Font-Size="8pt"
        GridLines="None" Height="22px" PageSize="2" Style="z-index: 104; left: 13px;
        position: absolute; top: 215px" Width="1179px">
        <PagerSettings Mode="NumericFirstLast" Position="Top" />
        <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
        <EmptyDataRowStyle Font-Size="Small" ForeColor="Red" />
        <Columns>
            <asp:BoundField DataField="DropID" HeaderText="DropID" InsertVisible="False" ReadOnly="True"
                SortExpression="DropID" Visible="False" />
            <asp:BoundField DataField="LocationID" HeaderText="LocationID" InsertVisible="False"
                ReadOnly="True" SortExpression="LocationID" Visible="False" />
            <asp:BoundField DataField="OrderID" HeaderText="OrderID" />
            <asp:BoundField DataField="ProductID" HeaderText="ProductID"  />
            <asp:TemplateField HeaderText="Unit Price">
                <ItemTemplate>
                    &nbsp;<asp:TextBox ID="txtUnitPrice" runat="server" ForeColor="Blue" Width="80px" TabIndex="1" ></asp:TextBox>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100px" />
                <HeaderStyle ForeColor="Red" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Quantity">
                <ItemTemplate>
                    <asp:TextBox ID="txtQuantity" runat="server" ForeColor="Blue" Width="50px" TabIndex="2"  ></asp:TextBox>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="65px" />
                <HeaderStyle ForeColor="Red" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Discount">
                <ItemTemplate>
                    <asp:TextBox ID="txtDiscount" runat="server" ForeColor="Blue" Width="80px" TabIndex="3" ></asp:TextBox>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100px" />
                <HeaderStyle ForeColor="Red" />
            </asp:TemplateField>
            

        </Columns>
        <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
        <PagerStyle BackColor="#C6C3C6" Font-Bold="False" Font-Size="8pt" ForeColor="Red"
            HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
    </asp:GridView>
        &nbsp; &nbsp; &nbsp;&nbsp;
    <asp:SqlDataSource ID="dsOrderDetails" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        SelectCommand="select OrderID,ProductID,UnitPrice,Quantity,Discount from [Order Details] where OrderID=@OrderID">
        <SelectParameters>
            <asp:QueryStringParameter Name="OrderID" QueryStringField="OrderID" />
        </SelectParameters>
    </asp:SqlDataSource>
    &nbsp;
<asp:Button ID="btnUpdate" runat="server" Style="z-index: 110; left: 864px; position: absolute;
        top: 416px" Text="Update" Width="139px" CausesValidation="true"  OnClientClick="return ValidateParameters();" />
    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;
        &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;

    </div>
    </form>
</body>
</html>

Open in new window

0
Comment
Question by:jxharding
  • 6
7 Comments
 
LVL 2

Expert Comment

by:Lord_Death
ID: 36560326
Its because other pages wont Render on client side and when nothing is physically in your page JavaScript wont be able to validate.

you can not use Client Side Validation with GridView Paging ,

you have to do the paging on client side to validate it. but you will load  whole data and loose your performance.
0
 

Author Comment

by:jxharding
ID: 36560377
thanks, im only trying to validate the controls that are on the page like you mention,
whilst in the case that there is only one page

there are 2 rows

row1
row2


in the case that there are more than one pages there are still two rows visible to the user
row1
row2

i'd only like to validate the page that is currently displayed and for which the rendering has taken place.

is it thus that client side validation can never work, if the gridview has multiple pages?
0
 

Author Comment

by:jxharding
ID: 36560444
i have got a working demo where validation works on client side with more than one page
theres something with the original code i posted which is not working

0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:jxharding
ID: 36560488
please find attached working demo i setup where validation works on client side with more than one page

Imports System.Data

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Me.GridView1.DataBind()

            Dim SQLConnection As New SqlClient.SqlConnection
            Dim strSQLConn As String = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")
            SQLConnection.ConnectionString = strSQLConn
            SQLConnection.Open()
            Dim SQLCmd As New SqlClient.SqlCommand
            SQLCmd.Connection = SQLConnection
            SQLCmd.CommandType = CommandType.Text
            SQLCmd.CommandText = "SELECT o.[OrderID], o.[CustomerID], o.[OrderDate], o.[RequiredDate], o.[ShippedDate], [ShipCity], o.[ShipCountry],o.[OrderID],sum(d.Quantity) as TotalQty FROM [Orders] o inner join [Order details] d on o.orderid = d.orderid group by o.[OrderID], o.[CustomerID], o.[OrderDate], o.[RequiredDate], o.[ShippedDate], [ShipCity], o.[ShipCountry],o.[OrderID]"

            Dim SQLTable As SqlClient.SqlDataReader
            SQLTable = SQLCmd.ExecuteReader
            While SQLTable.Read
                For Each row As GridViewRow In Me.GridView1.Rows
                    If Me.GridView1.DataKeys(row.RowIndex).Item("OrderID") = SQLTable.Item("OrderID") Then
                        CType(row.FindControl("txtOrderID"), TextBox).Text = SQLTable.Item("OrderID")
                        CType(row.FindControl("txtCustomerID"), TextBox).Text = SQLTable.Item("CustomerID")
                    End If
                Next
            End While
            SQLTable.Close()


        End If
    End Sub
    Private Sub EnterDetails()


    End Sub
    Private Sub RetrieveDetails()
        Try
            Dim SQLConnection As New SqlClient.SqlConnection
            Dim strSQLConn As String = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")
            SQLConnection.ConnectionString = strSQLConn
            SQLConnection.Open()
            Dim SQLCmd As New SqlClient.SqlCommand
            SQLCmd.Connection = SQLConnection
            SQLCmd.CommandType = CommandType.Text
            SQLCmd.CommandText = "SELECT o.[OrderID], o.[CustomerID], o.[OrderDate], o.[RequiredDate], o.[ShippedDate], [ShipCity], o.[ShipCountry],o.[OrderID],sum(d.Quantity) as TotalQty FROM [Orders] o inner join [Order details] d on o.orderid = d.orderid group by o.[OrderID], o.[CustomerID], o.[OrderDate], o.[RequiredDate], o.[ShippedDate], [ShipCity], o.[ShipCountry],o.[OrderID]"

            Dim SQLTable As SqlClient.SqlDataReader
            SQLTable = SQLCmd.ExecuteReader
            While SQLTable.Read
                For Each row As GridViewRow In Me.GridView1.Rows
                    If Me.GridView1.DataKeys(row.RowIndex).Item("OrderID") = SQLTable.Item("OrderID") Then
                        CType(row.FindControl("txtOrderID"), TextBox).Text = SQLTable.Item("OrderID")
                        CType(row.FindControl("txtCustomerID"), TextBox).Text = SQLTable.Item("CustomerID")
                    End If
                Next
            End While
            SQLTable.Close()
        Catch ex As Exception

        End Try
    End Sub
    Protected Sub GridView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.DataBound
        RetrieveDetails()
    End Sub
    Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
        EnterDetails()
    End Sub
    Protected Sub GridView1_PageIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.PageIndexChanged
        Try
            RetrieveDetails()
        Catch ex As Exception

        End Try
    End Sub


End Class
________________

<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<telerik:RadCodeBlock ID="RadBlock1" runat="server">
<script language="javascript" type="text/javascript"> 
       function ValidateParameters()
        {
              var grid = document.getElementById("<%= GridView1.ClientID %>");
                         if (grid.rows.length > 0)
                         {
                            //loop starts from 1. rows[0] points to the header.
                            for (i=1; i<grid.rows.length; i++)
                            {
                                var cellCheckRequiredValue1 = grid.rows[i].cells[0].childNodes[0].value;
                                var cellCheckRequiredValue2 = grid.rows[i].cells[1].childNodes[0].value;
                                alert(cellCheckRequiredValue1);
                                alert(cellCheckRequiredValue2);
                                if (cellCheckRequiredValue1 == "" || cellCheckRequiredValue2 == "")
                                {
                                    alert("Please Enter All Supplied Values As Indicated");
                                    return false;
                                }
                            
                            }
                         }
        }
 </script>
</telerik:RadCodeBlock>
   
    <div>
        <asp:Button ID="Button1" runat="server" Text="Fill" />
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" DataSourceID="SqlDataSource1" PageSize="3" DataKeyNames="OrderID">
                <Columns>
                  <asp:TemplateField HeaderText="OrderID">
                <ItemTemplate>
                    <asp:TextBox ID="txtOrderID" runat="server" ForeColor="Blue" Width="80px" TabIndex="6"></asp:TextBox>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100px" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="CustomerID">
                <ItemTemplate>
                    <asp:TextBox ID="txtCustomerID" runat="server" ForeColor="Blue" Width="50px" TabIndex="7"></asp:TextBox>
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="60px" />
            </asp:TemplateField>
                </Columns>
        </asp:GridView>
    
    </div>
                  <asp:SqlDataSource ID="SqlDataSource1" runat="server"  
                     ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"  
                     SelectCommand="SELECT o.[OrderID], o.[CustomerID], o.[OrderDate], o.[RequiredDate], o.[ShippedDate], [ShipCity], o.[ShipCountry],o.[OrderID],sum(d.Quantity) as TotalQty FROM [Orders] o inner join [Order details] d on o.orderid = d.orderid group by o.[OrderID], o.[CustomerID], o.[OrderDate], o.[RequiredDate], o.[ShippedDate], [ShipCity], o.[ShipCountry],o.[OrderID]">  
                 </asp:SqlDataSource>  
        <asp:Button ID="btnUpdate" runat="server" Text="Update" OnClientClick="return ValidateParameters();"  />
</asp:Content>

Open in new window

0
 

Author Comment

by:jxharding
ID: 36560530
i forgot to mention

once you've run the initial app to see that the client side validation works,
please change the orderid to 10250 and press enter, to see an order with more than one page
0
 

Accepted Solution

by:
jxharding earned 0 total points
ID: 36564941
it looks like the thing bombs out when the  PagerSettings  position is set to Top

  <PagerSettings Mode="NumericFirstLast" Position="Top" />
         
0
 

Author Closing Comment

by:jxharding
ID: 36591877
After hours, i found that the Position at the top, caused the crash
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now