How to enable a button if regex expression is valid - asp.net

I have a page on which there are two textboxes that have a regular expression on them.
ASPX Code TextBox 1
<asp:TextBox ID="txtCasesInsert" runat="server" Width="50px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvCases" ControlToValidate="txtCasesInsert" ValidationGroup="InsertRecord"
runat="server" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexCases" ControlToValidate="txtCasesInsert"
ValidationExpression="[0-9]+(,[0-9]+)*" ForeColor="Red" ErrorMessage="Please seperate numbers with a comma"
runat="server" />
ASPX Code TextBox 2
<asp:TextBox ID="txtPremiumInsert" runat="server" Width="50px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPremium" ControlToValidate="txtPremiumInsert"
ValidationGroup="InsertRecord" runat="server" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexPremium" ControlToValidate="txtPremiumInsert"
ValidationExpression="[0-9]+(,[0-9]+)*" ForeColor="Red" ErrorMessage="Please seperate numbers with a comma"
runat="server" />
The regular expression works as intended for both text boxes.
What I need now is to be able to check the text being inputted into those text boxes and if the regular expression is valid, then enable my Insert button, otherwise, keep the button disabled.
Insert Button
<asp:Button ID="btnInsertRecord" Width="100px" Height="25px" runat="server" Text="Add Record"
CssClass="buttonBlue" ValidationGroup="InsertRecord" />
The reason I want to do this, is because when the regex has an error, the page still allows the user to insert data so I thought of disabling the button if the regex isn't successfull to prevent this.
I tried this C# If regex doesn't match then do something and I've also read up on Microsofts Regex documentation to learn more about what I can do with Regex's but I haven't found any information related to what I need.
I also tried creating a function with a TextChanged method hooked onto the textboxes but it didn't work. No error messages, just the button wasn't disabling when I inputted a wrong string. That's the problem I'm also having now with my current code. It's like nothing is happening. I've hooked the debugger on the _premiumMatch.Success line but again, nothing is happening, it just lets me proceed. When I created the TextChanged method for my button, I also tried adding it into my Page Load method but that disabled the button straight away.
Current VB Code (Example with one of the text boxes)
Dim _regex As Regex = New Regex("[0-9]+(,[0-9]+)*")
Dim _premiumMatch = _regex.Match(txtPremiumInsert.Text)
If _premiumMatch.Success Then
Try
Company.Applications.ProductionEngine.BusinessAccess.ExcelFileContentUploadBusinessAccess.InsertLimitInsurance(_branch,
_premium,
_cases,
_ddlMonths,
_ddlYear)
Catch ex As Exception
InformationBox.ShowErrorMessage("Record not added. Please try again")
End Try
loadLimitInsurances()
InformationBox.ShowSuccessMessage("New Record Inserted")
txtBranchInsert.Text = ""
txtPremiumInsert.Text = ""
txtCasesInsert.Text = ""
End If
Not sure what I'm doing wrong. Any suggestions? The above VB code, for now is in my buttons click event but even with an invalid regex, when I click the insert is still performed.
First Edit
Just tried calling the below function in my page load but the button disables straight away and does not become enabled if I input a valid regex. Again, example is for one textbox.
Protected Friend Sub CheckPremium() Handles txtPremiumInsert.TextChanged
Dim _regex As Regex = New Regex("[0-9]+(,[0-9]+)*")
Dim _match As Match = _regex.Match(txtPremiumInsert.Text)
If _match.Success Then
btnInsertRecord.Enabled = True
Else
btnInsertRecord.Enabled = False
End If
End Sub
Second Edit
I have tried the above code and I've activated AutoPostBack on the textbox and still when I type an invalid expression it postbacks and activates my button.

Try this code:
Dim _regex As Regex = New Regex("[0-9]+(,[0-9]+)*")
Dim FoundMatch As Boolean = _regex.IsMatch(textPremiumInsert.Text)
If FoundMatch = True Then
Try
Company.Applications.ProductionEngine.BusinessAccess.ExcelFileContentUploadBusinessAccess.InsertLimitInsurance(_branch,
_premium,
_cases,
_ddlMonths,
_ddlYear)
Catch ex As Exception
InformationBox.ShowErrorMessage("Record not added. Please try again")
End Try
loadLimitInsurances()
InformationBox.ShowSuccessMessage("New Record Inserted")
txtBranchInsert.Text = ""
txtPremiumInsert.Text = ""
txtCasesInsert.Text = ""
End If
The code above uses the Regex.IsMatch method to compare the string passed with the regex pattern. It returns true if the string matches the Regex pattern.

Related

ASP:NET - GridVIEW - DropDownList selectedvalue

I am new at this forum though I have passed many years looking for answers into it. Now,I will like your help to solve an issue. I am following this link to make my own DropDown List in my Grid and works fine until this line:
ddlCities.Items.FindByValue(country).Selected = True
here,I have got error:
Object reference not set to an instance of an object.
but my code is right in affected fields:
this is relevant code in Code Behind:
Protected Sub RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow AndAlso grdLinea.EditIndex = e.Row.RowIndex;
Dim ddlCities As DropDownList = DirectCast(e.Row.FindControl("ddlFacturarA"), DropDownList)
' Create the command with the sproc name and add the parameter required'
ddlCities.DataSource = GetData("select UPPER(DSCA_ZONA)as Zona from tb_personal where dsca_Zona <> 'NULL'group by dsca_zona order by dsca_zona")
ddlCities.DataTextField = "Zona"
ddlCities.DataValueField = "Zona"
ddlCities.DataBind()
'Add Default Item in the DropDownList
'ddlCountries.Items.Insert(0, New ListItem("Please select"))
Dim country As String = Trim(CType(e.Row.FindControl("lblFacturarA"), Label).Text)
ddlCities.Items.FindByValue(country).Selected = True
End If
End Sub
and this is affected code in design mode:
<EditItemTemplate >
<asp:label ID="lblFacturarA" Value ='<%# Eval("facturar_a")%>' Visible ="false" runat="server" />
<asp:DropDownList
ID="ddlFacturarA"
CssClass="txt"
runat="server"
AutoPostBack="True" ValidationGroup="rfNewLineEmpty">
</asp:DropDownList>
<asp:RequiredFieldValidator
ID="rfNewLineFacturarA"
runat="server"
ErrorMessage="Obligatorio"
ValidationGroup="rfNewLine"
SetFocusOnError="True"
ControlToValidate="ddlFacturarA">
</asp:RequiredFieldValidator>
</EditItemTemplate>
I know I am new at ASP.NET and maybe I am loosing something by the way, but I have been round this code for two days and don't see light.
can you tell me something about reason for this error?
please,let me know if you need more detailed information to solve this.
thanks in advance
If you are sure that error is on line ddlCities.Items.FindByValue(country).Selected = True and country item is in dropdown list, I suggest you double check that is there white space or upper/lower case difference in dropdown list item and country variable.
because FindByValue finds exact item and it is case sensitive.
You should try changin query to RTRIM(LTRIM(UPPER(DSCA_ZONA))) as Zona
and
ddlCities.Items.FindByValue(country.ToUpper()).Selected = True
Sorry for delay as I been outside, i think i've solved in this way
Dim country As String = Trim(CType(e.Row.FindControl("lblFacturarA"), Label).Text)
ddlCities.Items.Insert(0, country)
and now it's working fine, Do you think this is a valid way?
many thanks!!!

ASP:CustomValidator continues to execute after error message thrown

ASP:CustomValidator continues to execute the rest of my code after the the Validator renders as False. I have a few textboxes (Name, Date, IdNumber, OtherShit)
Here's some code:
<span class="grouping" id="span1" runat="server">
<label>
ID Number</label>
<asp:TextBox ID="tbIdNumber" runat="server" MaxLength="6" Columns="10"></asp:TextBox>
<asp:CustomValidator ID="CustomValidatorIdNumber" runat="server" ErrorMessage="Please enter date."
ControlToValidate="tbIdNumber" OnServerValidate="CustomValidatorLocation_ServerValidate1"> </asp:CustomValidator>
</span>
Followed by the back end code controlling the Validator:
Protected Sub CustomValidatorLocation_ServerValidate1(source As Object, args As ServerValidateEventArgs) Handles CustomValidatorIdNumber.ServerValidate
Dim currentUserId = Things.AuthenticatedData.Get_CurrentUser.Id
If (Convert.ToString(args.Value)) Is currentUserId Then
args.IsValid = True
ElseIf (Convert.ToString(args.Value)) IsNot currentUserId And bdpDate.IsNull Then
args.IsValid = False
End If
End Sub
So each person logged in has an ID that is known to other users. FYI this is a search filter. Basically what I would like to do is this: if the user types in their own ID, then everything is fine and will continue to execute through the code. If the user types in another users ID, they also need to include a date. If no date is include, it throws the error message when they click "Search" (but does not execute the search) until they put in a date. Currently it does all that, but still executes the search. Meh... Help please...
Make sure you put the Page.IsValid() on the right instance of the btnClick... fml. Works perfect now.

Asp.net VB Test value in GridView

I have found heaps of solutions for this in C# but when you are dealing with FindControls and trying to pull a value out of the GridView the C# doesn't help and the translated code doesn't work.
I have this gridview:
<asp:GridView ID="WIPListGrid" runat="server" DataSourceID="WIPDataSource"
CssClass="site" AutoGenerateColumns="False"
Width="95%" DataKeyNames="Masterid_Action" onrowdatabound="WIPListGrid_RowDataBound">
<Columns>
<asp:BoundField DataField="Action Due Date" HeaderText="Action Due Date"
SortExpression="Action Due Date" />
</Columns>
</asp:GridView>
and I have this in vb:
Protected Sub WIPListGrid_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles WIPListGrid.RowDataBound
Dim DueDate As Label = DirectCast(e.Row.FindControl("Action Due Date"), Label)
'do what ever you want to do here using the value of your label
MsgBox("Due Date = " & DirectCast(e.Row.FindControl("Action Due Date"), Label))
End Sub
Error message is Operator & is not defined for types 'String' and 'System.Web.UI.WebControls.Label'
This is a remedial example of what I ~really~ want to do. Above I just want to display what is contained in DueDate to see what format it is in so I can test it against other values. but it won't work. It appears the the contents of Action Due Date is not a string... so, what am I missing?
I have tried to set the value equal to a string but got the same problem, the Label isn't a string...
How do I find out what's in there in order to evaluate it?
17/01/2013 edit: Keeping this active as I still do not have my issue resolved.
18/01/2013 edit:
vb.net code is now
Protected Sub WIPListGrid_ROWDataBound(sender as Object,
e As System.Web.UI.Webcontrols.GridViewRowEventArgs) Handles WIPListGrid.RowDataBound
Dim DueDate As Label = DirectCast(e.Row.FindControl("Action Due Date"), Label)
'do what ever you want to do here using the value of your label
MsgBox("Due Date = " & DueDate.Text)
End Sub
But now I get an error that the Object isn't instantiated and its pointing to the msgbox line in the code. I thought that I instantiated it when I dim it as a Label...
The official error is:
"Object reference not set to an instance of an object."
the troubleshooting tips say to
1) Use the "new" keyword to create an object instance
2) Check to determine if the object is null before calling the method
I tried the "new" option and got an error that says the variable has already been declared.
So now I want to check to determine if the object is null and can't figure out how.
I've tried testing: DirectCast(e.Row.FindControl("action due date"), Label) <> ""
but got an error: Overload resolution failed because no accessible '<>' can be called with these arguments.
How do I test to see if the object is null?
The value shouldn't be null (the database doesn't allow it to be null), BUT this could be the crux of my issue...
Any help?
When working with controls, you have to point out that you want that value inside your control.
In your case, you're just going for the label-control itself (not the text inside).
For example:
Dim myControl As Label = DirectCast(e.Row.FindControl("myControl"), Label)
MsgBox("MyText = " & myControl.Text)
Hope this helps.
The problem is you are using a BoundField so there is no control to find. Change it to a templatefield and this will work.
<asp:GridView ID="WIPListGrid" runat="server" DataSourceID="WIPDataSource"
CssClass="site" AutoGenerateColumns="False"
Width="95%" DataKeyNames="Masterid_Action" onrowdatabound="WIPListGrid_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Action Due Date">
<ItemTemplate>
<asp:Label ID="lblActionDueDate" runat="server" Text='<%# Bind("[Action Due Date]") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
For Your Row DataBound Event use
Dim DueDateLabel As Label = DirectCast(e.Row.FindControl("lblActionDueDate"), Label)
'Check Label Exists
If DueDateLabel IsNot Nothing Then
Dim DueDateText As String = DueDateLabel.Text
MsgBox(String.Format("Due Date {0}", DueDateText))
End If

ASP.NET Losing listbox binding on viewchange?

Ok so what seems like a basic problem is getting the better of me and my exstensive google efforts have come up short. Perhaps I don't understand enough to ask the right questions.
Here's my problem:
I have a formview control, or rather a series of them, each page displaying entry from previous forms, for a higher level access to approve/edit as needed. So, on form "B", I have the contents of form "A" and the blank part of "B" to filled out...So two seperate fromviews on the page.."A" and "B"
That works fine, the issue is when I change the mode to edit previous entry. So if I have a button or the default linkbutton to change from ReadOnly to Edit I not only lose bindings but any efforts to counteract that have left me with issues when I postback.
DUE TO LENGTH I'M LEAVING SOME CODE OUT
On my button I'm using FormView2.ChangeMode(FormViewMode.Edit) to change view, the default link button I've not changed
Bindings on my listboxes are setup like:
If Not Page.IsPostBack Then
'pulling bindings from table
cmd = New OleDbCommand("SELECT * FROM mslToi", objCon)
objReader = cmd.ExecuteReader
lst1.DataValueField = "listing"
lst1.DataTextField = "listing"
lst1.DataSource = objReader
lst1.DataBind()
'pre-selecting input data from form "A"
cmd = New OleDbCommand("SELECT [type_of_injury] FROM S2childToi WHERE ID = " & qs & "", objCon)
objReader = cmd.ExecuteReader
Do While objReader.Read
For Each y As ListItem In lst1.Items
If y.Text = objReader.Item(0) Then
y.Selected = True
End If
Next
Loop
end if
In the page load event.
MARKUP FOR THE FORMVIEW AS ASKED
<asp:FormView ID="FormView2" runat="server"
Width="100%" DataSourceID="AccessDataSource4">
<ItemTemplate>
</ItemTemplate>
<EditItemTemplate>
</EditItemTemplate>
</asp:FormView>
'''that is the short and sweet of the formview markup as requested. It may also be worth noting that it doesn't matter what mode I start in, if I change modes it equals same result'''
That works fine so far...it's when I change view to Edit that my listbox appears to no longer be bound (controls appear but have no content). My thought is that obviously I'm blocking out my code from postback events (I have a reason for this). I can use this code (without the If Not Page.IsPostBack) to force the selections and bindings but whenever I postback they will defualt to the table data, which can't happen, each listbox needs to postback so I can check for a certain selection. So what happens is the user input is trumped. Short and sweet.
I'm sorry that I can't explain better, any advice is much appreciated. If I can asnwer any questions or post code let me know.
Try this:
<asp:FormView ID="FormView1" runat="server">
<ItemTemplate>
<asp:ListBox ID="ListBoxReadonly" runat="server"></asp:ListBox>
</ItemTemplate>
<EditItemTemplate>
<asp:ListBox ID="ListBoxEdit" runat="server"></asp:ListBox>
</EditItemTemplate>
</asp:FormView>
Then, in your FormView's databound event, bind the data into your listbox depending on the current view.
Protected Sub FormView1_DataBound(sender As Object, e As EventArgs) Handles FormView1.DataBound
Dim myListBox As ListBox
If FormView1.CurrentMode = FormViewMode.ReadOnly Then
myListBox = DirectCast(FormView1.FindControl("ListBoxReadonly"), ListBox)
ElseIf FormView1.CurrentMode = FormViewMode.Edit Then
myListBox = DirectCast(FormView1.FindControl("ListBoxEdit"), ListBox)
End If
If myListBox IsNot Nothing Then
myListBox.DataValueField = "listing"
myListBox.DataTextField = "listing"
myListBox.DataSource = GetListingData()
myListBox.DataBind()
' your pre-select code here...
End If
End Sub

Getting edit value from ListView

I'm missing something here, but I've stared at it too long to see it. I've got a simple ListView, with the typical Edit/Update/Cancel buttons. I've got the following set up in my EditITemTemplate when the row goes into edit mode:
<EditItemTemplate>
<asp:Label ID="AccountIdLabel" runat="server" Text='<%#Eval("lan_id")%>' />
<asp:TextBox ID="EmployeeIdTextBox" runat="server" Text='<%#Eval("emp_id")%>' Columns="5" />
</EditItemTemplate>
At this point the user types a value in the EmployeeIdTextBox. When they press Update, it's trying to do the following:
Private Sub ListView_ItemUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewUpdateEventArgs) Handles EmployeeListView.ItemUpdating
Dim accountId = CType(EmployeeListView.EditItem.FindControl("AccountIdLabel"), Label).Text
Dim employeeId = CType(EmployeeListView.EditItem.FindControl("EmployeeIdTextBox"), TextBox).Text
UpdateMap(accountId, employeeId)
EmployeeListView.EditIndex = -1
GetData()
End Sub
The problem is that "employeeId" is coming back with the original value in the text box, not what the user entered. What am I missing?
UPDATE: Found it. As usual, caused by other code not included here in an effort to ask a simple question. :)
Found it - I had code in the ItemCommand event that was handling other events, but it was doing the GetData() at the end regardless of the command, so basically the data was being refreshed right before the ItemUpdating event fired. I tightened up ItemCommand, and it's now working as expected.
I think this is because the ItemUpdating event fires before the ListView updates the record. You probably want to put this code in the ItemUpdated event instead.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemupdating.aspx

Resources