【问题标题】:Adapt text validation function to consider selected text调整文本验证功能以考虑选定的文本
【发布时间】:2010-06-04 00:31:20
【问题描述】:

我有这个函数,它评估文本框(或组合框或掩码文本框)控件的内容,并结合 KeyPress 事件,将允许或禁止输入。它对于只有数字输入有效的日期或文本框非常有用。如果在函数调用中指定,它允许在单个小数点后设置一组数字。如果文本框已满,它还允许退格字符。

我希望它允许我在文本框已满但突出显示一个或多个字符时输入有效文本(因此将被按键字符替换。谁能告诉我如何做到这一点,请问?

''' <summary>
''' Validates that input is numeric.  
''' Allows one decimal place unless intDecimal is less than 1
''' Will allow a set number of numbers after the decimal place.
''' </summary>
''' <param name="strKeyPress">The key which has been pressed</param>
''' <param name="strText">Current text of the textbox</param>
''' <param name="intPosition">Current cursor position in textbox</param>
''' <param name="intDecimal">Number of decimal places desired.</param>
''' <returns>Boolean: true means that input is numeric, false means it is not.</returns>
''' <remarks>Used with a keypress event to validate input.  Do not handle input if function returns false.</remarks>
Public Function InputIsNumeric(ByVal strKeyPress As String, ByVal strText As String, ByVal intPosition As Integer, ByVal intDecimal As Integer) As Boolean
    Dim dot As Integer
    Dim ch As String
    Dim returnValue As Boolean

    If Not Char.IsDigit(CType(strKeyPress, Char)) Then returnValue = True
    If strKeyPress = "-" And intPosition = 0 Then returnValue = False 'allow negative number 
    If strKeyPress = "." And strText.IndexOf(".") = -1 And intDecimal > 0 Then returnValue = False 'allow single decimal point 
    dot = strText.IndexOf(".")
    If dot > -1 Then 'limit to set decimal places 
        ch = strText.Substring(dot + 1)
        If ch.Length > (intDecimal - 1) Then returnValue = True
    End If
    If strKeyPress = Chr(8) Then returnValue = False 'allow Backspace 
    Return returnValue
End Function

【问题讨论】:

    标签: .net vb.net validation


    【解决方案1】:

    您可以添加几个参数(intLengthOfHighlightedText 和 intLengthOfControl)并传递 Textbox.SelectedText 和 TextboxName.MaxLength(假设单行文本控件)。然后在你的函数中解决这个问题。否则,您可以传递整个文本框控件的值(使其重载或为组合框完成工作等)。

    【讨论】:

    • 我喜欢只传入文本框的想法。我可能只是将 ComboBox 或 MTB 转换为文本框,对吧?
    • 我不知道铸造,因为组合框是集合。如果要传递控件,请使函数重载(支持不同类型参数的过程/函数)。或者,您可以让函数接受通用控件类型并使用反射来获取文本属性。
    猜你喜欢
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 2013-06-07
    • 2018-09-06
    • 1970-01-01
    • 2011-12-21
    相关资源
    最近更新 更多