【问题标题】:Only allow a specific Value Format in a Textbox C# WinForms仅允许文本框 C# WinForms 中的特定值格式
【发布时间】:2019-08-24 09:26:24
【问题描述】:

我想确保我的文本框的输入是特定格式的。

+101.800
-085.000
+655.873

正确的长度以及 +/- 符号对于过程中的通信很重要。

我考虑过使用 MaskedTextbox,但如果我正确理解文档,这不会强制用户添加 +/- 符号。

【问题讨论】:

  • 因此,如果我通过您的示例正确理解,您只想接受小数点前三位数字和三位小数的正值或负值?请具体。
  • 是的,您理解正确,小数点前三位,小数点后三位。在前面我也需要 + 或 - 符号。
  • 试试下面的掩码#000.000

标签: c# winforms textbox string-formatting


【解决方案1】:

您可以在离开文本框后在离开事件中写入检查值,如果该值是错误的值以引起用户注意,则将文本颜色设置为红色,并禁用提交按钮以防止在以正确格式写入数字之前按下按钮。

private void myInput_Leave(object sender, EventArgs e)
{
    Regex r = new Regex(@"^[+-]?[0-9]{3}\.[0-9]{3}$");
    Match m = r.Match(InputTextbox.Text);
    if (!m.Success)
    {
         myInput.ForeColor =  Color.Red;  // Text color will go red
         submitBtn.Enabled = false;  // Submit button is disabled now
    }
    else
    {
         myInput.ForeColor =  Color.Black;
         submitBtn.Enabled = true; // Submit button is enabled now
    }
}

【讨论】:

  • 你的帮助
  • @Shining @ 符号添加到正则表达式。谢谢
【解决方案2】:

我使用了@Max Voisard 的正则表达式,但它给了我一个未知 Escape Sequnece 的错误,所以我添加了 @Symbol 使其对我有用。

private void textBox18_Validating(object sender, CancelEventArgs e)
        {
            Regex r = new Regex(@"^[+-]?[0-9]{3}\.[0-9]{3}$");

            Match m = r.Match(((TextBox)sender).Text);
            if (!m.Success)

            {
                // Cancel the event and select the text to be corrected by the user.
                e.Cancel = true;
                ((TextBox)sender).Select(0, ((TextBox)sender).Text.Length);



            }
        }

【讨论】:

    【解决方案3】:

    试试这个正则表达式:

    private void InputTextbox_Leave(object sender, EventArgs e)
    {
        Regex r = new Regex(@"^[+-]?[0-9]{3}\.[0-9]{3}$");
        Match m = r.Match(InputTextbox.Text);
        if (m.Success)
        {
            // Code
        }
    }
    

    【讨论】:

    • 您应该在离开事件或更相关的内容中编写此内容,当文本正在更改时用户正在输入并且我们无法检查该文本。
    • 欢迎您的快速解答
    猜你喜欢
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 2012-09-18
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多