代码之家  ›  专栏  ›  技术社区  ›  Tom

ASP.net VB-修剪/替换问题

  •  0
  • Tom  · 技术社区  · 14 年前

    我试图在提交表单时删除文本字段中的所有空格,以便邮政编码字段的内容与数据库中的内容匹配。。。

    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
    

    因此,如果数据库中的邮政编码是AB12CD,而用户键入AB12CD,则提交表单时会删除空格,并显示match语句。但这不管用。

    如果用户不包括空间,一切都可以正常工作。

    4 回复  |  直到 14 年前
        1
  •  1
  •   Joel Etherton    14 年前

    试着把它分成几个部分,这样你就能正确地计算字符串。在一行上执行所有这些操作的可读性较差,而且更容易出错。另外,不要使用带UCase、CStr、Len等的旧VB6表示法。它们在Microsoft.VisualBasic命名空间中仍然有效(MS向我们保证它不会出现在任何地方),但是只要熟悉.Net对象结构,您就会发现示例代码更容易翻译。

    ' 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
    
        2
  •  1
  •   Xaqron    14 年前

    那是因为 Ucase Replace 是实例方法。试试这个:

    tbPostcode.Text.Replace(" ","").ToUpper
    
        3
  •  1
  •   Hans Passant    14 年前

    创建临时控制台应用程序并运行以下代码:

    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
    

    上面说什么?

        4
  •  0
  •   abatishchev Karl Johan    14 年前

    Replace() 但是 String.Replace()

    推荐文章