如何在 vb.net 中输入时格式化文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1385624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 14:24:24  来源:igfitidea点击:

how to format text box during input in vb.net

vb.net

提问by Faizan Dosani

I have 200+ text boxes in vb.net application. Let me make it clear all are simple text boxes. now customer demand to have formatted number value while input or viewing record. With Format() i can play for viewing but during add/edit mode in text box (While user typing value) nothing happened I want this result 1234567.0090 to 1,234,567.0090 during input.

我在 vb.net 应用程序中有 200 多个文本框。让我说清楚所有都是简单的文本框。现在客户要求在输入或查看记录时格式化数值。使用 Format() 我可以播放以供查看,但在文本框中的添加/编辑模式期间(当用户输入值时)什么也没有发生,我希望在输入期间将结果 1234567.0090 变为 1,234,567.0090。

or guide me any way by which i change all text boxes to mask textboxes through any tool or code.

或指导我通过任何工具或代码更改所有文本框以屏蔽文本框的任何方式。

Any help appreciated. Thanks in Advance.

任何帮助表示赞赏。提前致谢。

回答by MusiGenesis

First, I would recommend verystrongly that you try to talk your customer out of this requirement. Masked text boxes in general are a royal pain in the butt, both for the programmer andfor the end user. In my opinion, if you must format user input, it is far better to format whatever they have entered afterthe control loses focus than to attempt to format their input whilethey are still typing it.

首先,我建议非常强烈,你试图说服你的客户了这一要求。对于程序员最终用户来说,蒙面文本框通常是一个令人头疼的问题。在我看来,如果您必须格式化用户输入,最好在控件失去焦点格式化他们输入的任何内容,不是他们仍在键入尝试格式化他们的输入。

With either approach, the easiest way to do this is to create your own user control (unless you want to use a third-party control, which I wouldn't advise for this purpose for a bunch of reasons) that inherits from TextBox (instead of inheriting from UserControl). If you wish to format the text after the user has finished entering input and has moved on to another control, you can add an EventHandler to your control's LostFocus event and format their input there.

无论使用哪种方法,最简单的方法是创建您自己的用户控件(除非您想使用第三方控件,出于多种原因,我不建议为此目的)继承自 TextBox(而不是继承自 UserControl)。如果您希望在用户完成输入并移至另一个控件后格式化文本,您可以向控件的 LostFocus 事件添加一个 EventHandler 并在那里格式化他们的输入。

If, however, you wish to format as they're typing, you have a couple of grisly choices. First, you can handle the control's KeyPress or KeyDown events, and intercept-and-cancel non-numeric characters, or else format the overall Text property at this time. This is a common approach which often fails in unexpected ways, since it ends up not dealing with text that is copy-and-pasted into the control (which happens quite often in data-entry applications).

但是,如果您希望在他们输入时进行格式化,您有几个可怕的选择。首先,您可以处理控件的 KeyPress 或 KeyDown 事件,并拦截和取消非数字字符,或者此时格式化整个 Text 属性。这是一种经常以意想不到的方式失败的常见方法,因为它最终不处理复制并粘贴到控件中的文本(这在数据输入应用程序中经常发生)。

An alternative approach is to handle the TextChanged event, which will respond to both keyboard input and pasted-in text, and re-format the text on the fly. Since you're often changing the text as they type, your code needs to pay attention to the SelectionStart property (among others), so that you don't unexpectedly change the caret's position as the user is typing. Also, when you change your control's text property while formatting it, this change will itself produce another TextChanged event, so you need to be careful that you don't get stuck in an endless loop.

另一种方法是处理 TextChanged 事件,它将响应键盘输入和粘贴的文本,并即时重新格式化文本。由于您经常在键入时更改文本,因此您的代码需要注意 SelectionStart 属性(以及其他属性),以免在用户键入时意外更改插入符号的位置。此外,当您在格式化控件时更改控件的文本属性时,此更改本身会产生另一个 TextChanged 事件,因此您需要小心不要陷入无限循环。

To reiterate my main point, you will be much happier formatting in the LostFocus event, and so will your end users.

重申我的主要观点,您将在 LostFocus 事件中更快乐地格式化,您的最终用户也会如此。

Once you've written your control, you can just do a global replace in your code, substituting "MyMaskedTextBox" for "TextBox" (case-sensitivity is recommended here).

编写控件后,您只需在代码中进行全局替换,将“MyMaskedTextBox”替换为“TextBox”(此处建议区分大小写)。

Update:Here is some simple parsing/formatting code you can use in your TextBox's LostFocus event:

更新:这里有一些简单的解析/格式化代码,您可以在 TextBox 的 LostFocus 事件中使用:

double d;
TextBox tb = (TextBox)sender;
if (double.TryParse(tb.Text, out d))
{
    tb.Text = d.ToString("#,###,###,###.0000");
    tb.BackColor = SystemColors.Window;
}
else
{
    tb.BackColor = Color.Red;
}

This code will format the user's input as a number in the way that you require if the text entered can be parsed as a double. If the input is not a valid double, the text is left as is and the BackColor is changed to red. This is a good way of indicating invalid input to the user (as opposed to popping up a MessageBox).

如果输入的文本可以被解析为双精度数,则此代码将按照您要求的方式将用户的输入格式化为数字。如果输入不是有效的 double,则文本保持原样,BackColor 更改为红色。这是向用户指示无效输入的好方法(与弹出 MessageBox 相对)。

回答by Aneeth Thekkutte

Override these events in your text box derived custom control. But, remember no formating as they're typing,

在您的文本框派生自定义控件中覆盖这些事件。但是,记住不要在他们打字时格式化,

Protected Overrides Sub OnLostFocus(ByVal e As System.EventArgs)
    MyBase.OnLostFocus(e) 
    Me.Text = Strings.FormatNumber(Me.Text, _
                                      m_FormatNumDigitsAfterDecimal, _
                                      m_FormatIncludeLeadingDigit, _
                                      m_FormatUseParensForNegativeNumbers, _
                                      m_FormatGroupDigits)
End Sub
Protected Overrides Sub OnTextChanged(ByVal e As System.EventArgs)
    MyBase.OnTextChanged(e)
    If Me.Focused = False Then
        Me.Text = Strings.FormatNumber(Me.Text, _
                                       m_FormatNumDigitsAfterDecimal, _
                                       m_FormatIncludeLeadingDigit, _
                                       m_FormatUseParensForNegativeNumbers, _
                                       m_FormatGroupDigits)
    End If
End Sub

回答by Eliseo Pecchini

That′s another method.

那是另一种方法。

Private Sub TBItemValor_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TBItemValor.KeyPress
        If (Char.IsDigit(e.KeyChar) = False AndAlso Char.IsControl(e.KeyChar) = False AndAlso Char.IsPunctuation(e.KeyChar) = False) OrElse Not IsNumeric(Me.TBItemValor.Text & e.KeyChar) Then
            e.Handled = True
        End If
    End Sub

回答by Mohamad

Public Sub checktextbox2(txt As TextBox)
dim bg as string
For t = 1 To txt.Text.Length
        If txt.Text.Chars(txt.Text.Length - (txt.Text.Length - t)) = "." Then
            bq = txt.Text.TrimEnd(New String({"0", "."}))
            txt.Text = bq
            Exit For
        End If
    Next
end sub

this will format number in textbox as ###.###

这会将文本框中的数字格式化为###.###