Solved

RegularExpressionValidator in gridview always shows error on first update 2nd update works

Posted on 2008-06-14
1
1,739 Views
Last Modified: 2013-11-07
Simple gridview works great until I added the regular expression validator now when I edit field it always validates with an error.  When I click update again it saves fine. not using sqldatasource but doing everything in code behind.   Tried adding validator dynamically at runtime and got exactly same result.  kinda new to regular expression validator.  Kinda acts like I need to do a databind somewhere but I'm stuck.  Appreciate any help.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowFooter="True"
    DataKeyNames="MetricID" EmptyDataText="There are no data records to display." AllowPaging="True"
    AllowSorting="True" BackColor="#F7CB33">
    <Columns>
      <asp:TemplateField ShowHeader="False">
        <ControlStyle Width="60px"></ControlStyle>
        <ItemTemplate>
          <asp:LinkButton ID="LinkButtonEdit" runat="server" CausesValidation="False" CommandName="Edit"
            Text="Edit" OnClick="LinkButtonEdit_Click">
          </asp:LinkButton>
          <asp:LinkButton ID="LinkButtonDelete" runat="server" CausesValidation="False" CommandName="Delete"
            Text="Delete" OnClick="LinkButtonDelete_Click">
          </asp:LinkButton>
        </ItemTemplate>
        <EditItemTemplate>
          <asp:LinkButton ID="LinkButtonUpdate" runat="server" CausesValidation="False" CommandName="Update"
            Text="Update" OnClick="LinkButtonUpdate_Click">
          </asp:LinkButton>
          <asp:LinkButton ID="LinkButtonCancel" runat="server" CausesValidation="False" CommandName="Cancel"
            Text="Cancel" OnClick="LinkButtonCancel_Click">
          </asp:LinkButton>
        </EditItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="Metric ID" SortExpression="MetricID">
        <ItemStyle Width="90px"></ItemStyle>
        <ItemTemplate>
          <asp:Label ID="lblMetricID" runat="Server" ReadOnly="True" Text='<%# bind("MetricID")%>'>
          </asp:Label>
        </ItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="Metric Description" SortExpression="Description">
        <ItemTemplate>
          <asp:Label ID="Label1" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
          <asp:TextBox ID="txtDescription" runat="server" Text='<%# Bind("Description") %>'
            Width="350" CausesValidation="True">
          </asp:TextBox>
          <asp:RegularExpressionValidator ID="vTxtDescription" runat="server" ControlToValidate="txtDescription"
            Display="Dynamic" SetFocusOnError="true" ErrorMessage="Invalid, 40 characters max, use only letters and numbers or -$.,?_/"
            ValidationExpression="^([-$.,?_/\w\s]{40})$" EnableViewState="true">
          </asp:RegularExpressionValidator>
        </EditItemTemplate>
        <ItemStyle Width="400px" />
      </asp:TemplateField>
    </Columns>
  </asp:GridView>
 
 
Here is code behind
 
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Collections
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Collections.Specialized
Partial Class Products_VS_admin_vsMetricTable
    Inherits System.Web.UI.Page
Public Shared Table As New DataTable()
	Private ParameterArray As New ArrayList()
	Private sSortField As String = "MetricID"
	Private iPageIndex As Integer = 0
 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
	If Not IsPostBack Then
		'lblCompany.Text = Profile.CompanyIDDiv
		PopulateDataTable(sSortField)
	End If
End Sub
 
'Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
 
'If e.Row.RowType = DataControlRowType.DataRow Then
''Checking EditIndex should be same as current Row Index, then bind the validation controls in that particular row. 
 
'	If GridView1.EditIndex = e.Row.RowIndex Then
'		Dim regexpvalidator As New RegularExpressionValidator
'		regexpvalidator.ID = "RegularExpressionValidator1"
'		regexpvalidator.ValidationExpression = "^([-$.,?_/\w\s]{40})$"
'		regexpvalidator.ControlToValidate = "txtDescription"
'		regexpvalidator.ErrorMessage = "40 characters max, use only letters and numbers or -$.,?_/"
'		regexpvalidator.SetFocusOnError = True
'		e.Row.Cells(2).Controls.Add(regexpvalidator)
'	End If
 
'End If
 
'End Sub
 
Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
	iPageIndex = e.NewPageIndex
	GridView1.PageIndex = iPageIndex
	GridView1.DataSource = Table
	GridView1.DataBind()
End Sub
 
Protected Sub GridView1_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GridView1.RowCancelingEdit
	GridView1.EditIndex = -1
	GridView1.DataSource = Table
	GridView1.DataBind()
	Session("SelecetdRowIndex") = -1
End Sub
 
	Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating
		Dim Connection As SqlConnection = New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("SQL2005_484806_ghtsConnectionString1").ConnectionString)
		Dim row As GridViewRow = GridView1.Rows(e.RowIndex)
 
		Dim sMetricID As String = DirectCast(row.FindControl("lblMetricID"), Label).Text
		Dim sDescription As String = DirectCast(row.FindControl("txtDescription"), TextBox).Text
 
		ParameterArray.Clear()
		ParameterArray.Add(sMetricID)
		ParameterArray.Add(sDescription)
 
		Dim Query As String = ""
 
		If sMetricID = "" Then
			Query = GenerateInsertQuery()
		Else
			Query = GenerateUpdateQuery()
		End If
 
 
		Dim Command As SqlCommand = New System.Data.SqlClient.SqlCommand(Query, Connection)
 
		Try
				If Connection.State = ConnectionState.Closed Then
						Connection.Open()
				End If
				Command.ExecuteNonQuery()
		Catch se As SqlException
				'msg_lbl.Text = se.ToString()
				'MsgPanel.Visible = True
				Connection.Close()
		End Try
		GridView1.EditIndex = -1
		'CreateGridView()
		PopulateDataTable(sSortField)
	End Sub
 
	Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
		Dim Connection As SqlConnection = New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("SQL2005_484806_ghtsConnectionString1").ConnectionString)
		Dim row As GridViewRow = GridView1.Rows(e.RowIndex)
		Dim sMetricID As String = DirectCast(row.FindControl("lblMetricID"), Label).Text
 
		If sMetricID = "" Then
			Exit Sub
		End If
 
		ParameterArray.Clear()
		ParameterArray.Add(sMetricID)
 
		Dim Query As String = GenerateDeleteQuery()
		Dim Command As SqlCommand = New System.Data.SqlClient.SqlCommand(Query, Connection)
 
		Try
			If Connection.State = ConnectionState.Closed Then
				Connection.Open()
			End If
 
			Command.ExecuteNonQuery()
 
		Catch se As SqlException
			'msg_lbl.Text = se.ToString()
			'MsgPanel.Visible = True
			Connection.Close()
		End Try
 
		PopulateDataTable(sSortField)
	End Sub
 
	Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing
		GridView1.EditIndex = e.NewEditIndex
		GridView1.DataSource = Table
		GridView1.DataBind()
		Session("SelecetdRowIndex") = e.NewEditIndex
	End Sub
 
 
	Protected Sub msg_button_Click(ByVal sender As Object, ByVal e As EventArgs)
			'MsgPanel.Visible = False
	End Sub
 
Private Sub PopulateDataTable(ByVal SortField As String)
	Table = New DataTable()
	Dim Connection As SqlConnection = New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("SQL2005_484806_ghtsConnectionString1").ConnectionString)
 
	Dim adapter As New SqlDataAdapter("select MetricID, Description from [" & Profile.CompanyID & "Metrics] UNION SELECT NULL as MetricID, Null as Description ORDER BY " & SortField, Connection)
 
	Try
		adapter.Fill(Table)
		GridView1.DataSource = Table
		GridView1.DataBind()
	Catch ex As Exception
		'msg_lbl.Text = ex.ToString()
		'MsgPanel.Visible = True
		Connection.Close()
	End Try
End Sub
 
Private Function GenerateUpdateQuery() As String
	Dim TableName As String = DirectCast(Profile.CompanyID + "Metrics", String)
	Dim query As String = ""
	query = "UPDATE [" + TableName + "] SET Description = '" + ParameterArray(1) + "' WHERE [MetricID] = " + ParameterArray(0)
	Return query
End Function
 
Private Function GenerateInsertQuery() As String
	Dim TableName As String = DirectCast(Profile.CompanyID + "Metrics", String)
	Dim query As String = ""
	query = "INSERT INTO [" + TableName + "] (Description) VALUES ('" + ParameterArray(1) + "')"
	Return query
End Function
 
Private Function GenerateDeleteQuery() As String
	Dim TableName As String = DirectCast(Profile.CompanyID + "Metrics", String)
	Dim query As String = ""
	query = "DELETE FROM [" + TableName + "] WHERE [MetricID] = " + ParameterArray(0)
	Return query
End Function
 
Protected Sub GridView1_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles GridView1.Sorting
	sSortField = e.SortExpression.ToString
	PopulateDataTable(sSortField)
End Sub
 
 
 
Protected Sub LinkButtonEdit_Click(ByVal sender As Object, ByVal e As System.EventArgs)
	'AddHandler edit_button.Click, AddressOf edit_button_Click
End Sub
 
Protected Sub LinkButtonDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs)
 
End Sub
 
Protected Sub LinkButtonCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs)
 
End Sub
 
Protected Sub LinkButtonUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs)
 
End Sub
End Class

Open in new window

0
Comment
Question by:dweaver78
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 10

Accepted Solution

by:
SystemExpert earned 500 total points
ID: 21806518

I think you are required to check

vTxtDescription.Isvalid =true when you fire a update link

if it's shows for all row than will have to go through loop and make all
vTxtDescription.Isvalid=True

or remove it from

Page.Validators.Remove(vTxtDescription)  // After findeControl("vTxtDescription")
Thanks
Harshad Nayani
0

Featured Post

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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.…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.

717 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