ASP.net VB - Trim/Replace problem
I am trying to remove all spaces from a text field when a form is submitted so that the contents of the post code field ma开发者_JAVA百科tch those in a database...
If drSet5c.Tables(0).Rows(0).Item("post_code") = UCase(Replace(tbPostcode.Text, " ","")) Then
response.write("Postcodes match")
Else
response.write("Postcodes DON'T match")
End If
So if the postcode in the database is AB12CD and the user types AB1 2CD the space is removed on submitting the form and the match statement shows. This is not working though.
It all works fine if the user does not include the space.
Any ideas?
Try breaking it up into its parts so you can evaluate the string properly. Doing all of this on one line is less readable and more prone to error. Also, get away from using the old notation of VB6 with UCase, CStr, Len, etc. They're still valid within the Microsoft.VisualBasic namespace (and MS assures us that it's not going anywhere), but you'll find example code easier to translate if you just familiarize yourself with the .Net object structure.
' Get the row string out using ToString to force the typing
Dim rowPostCode As String = drSet5c.Tables(0).Rows(0).Item("post_code").ToString()
' Perform the case manipulation and replace function, then assign to new string
Dim tbPostCodeFormatted As String = tbPostcode.Text.Trim().ToUpper().Replace(" ", "")
' Perform the string comparison. Because we're ignoring case here, the ToUpper()
' used above may not be necessary
If rowPostCode.Equals(tbPostCodeFormatted, StringComparison.OrdinalIgnoreCase) Then
response.write("Postcodes match")
Else
response.write("Postcodes DON'T match")
End If
That's because Ucase
is a static (VB Shared) method while Replace
is an instance method. Try this:
tbPostcode.Text.Replace(" ","").ToUpper
Create a temporary Console application and run this code:
Module Module1
Sub Main()
Dim dbaseValue = "AB12CD"
Dim userInput = "AB1 2CD"
If UCase(dbaseValue) <> UCase(Replace(userInput, " ", "")) Then
Console.WriteLine("You need a new machine")
Else
Console.WriteLine("The bug is elsewhere")
End If
Console.ReadLine()
End Sub
End Module
What does it say?
Try to use not just Replace()
but String.Replace()
精彩评论