Link to home
Start Free TrialLog in
Avatar of jxharding
jxharding

asked on

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

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

Avatar of Lord_Death
Lord_Death

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.
Avatar of jxharding

ASKER

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?
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

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

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
ASKER CERTIFIED SOLUTION
Avatar of jxharding
jxharding

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
After hours, i found that the Position at the top, caused the crash