Advertisement

06.14.2008 at 07:16AM PDT, ID: 23485048
[x]
Attachment Details
[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

7.6

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

Asked by dweaver78 in Programming for ASP.NET, .NET, .NET Framework 2.x

Tags: ,

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.Start Free Trial
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
<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
[+][-]06.17.2008 at 12:20PM PDT, ID: 21806518

View this solution now by starting your 7-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

 

About this solution

Zones: Programming for ASP.NET, .NET, .NET Framework 2.x
Tags: asp.net, MS explorer 7
Sign Up Now!
Solution Provided By: SystemExpert
Participating Experts: 1
Solution Grade: B
 
 
 
Loading Advertisement...
20080716-EE-VQP-32 / EE_QW_2_20070628