【问题标题】:C# TextBox allow minus sign (-) only in the beginning of stringC# TextBox 只允许在字符串的开头使用减号 (-)
【发布时间】:2019-04-16 17:28:32
【问题描述】:

对不起,如果这是一个非常基本的问题,但我是 C# 新手,这是我的第一个 Windows 窗体应用程序。

在下面的代码中,我的 TextBox 只接受小数点“,”、减号“-”、数字,它还接受删除键和退格键的输入(如果我错了,请纠正我)。所以我可以输入和删除数字:

-12.31
-.31

问题是我还可以输入如下内容:

12-

有没有办法只在字符串的第一个字符时输入“-”?我尝试了谷歌,并试图想出一些东西,但似乎没有任何效果。

感谢您的宝贵时间。

private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsDigit(e.KeyChar) && (e.KeyChar != ',') && (e.KeyChar != '-') && (e.KeyChar != (char)8))
        {
            e.Handled = true;
        }
        if ((e.KeyChar == ',') && ((sender as TextBox).Text.IndexOf(',') > -1))
        {
            e.Handled = true;
        }

        if ((e.KeyChar == '-') && ((sender as TextBox).Text.IndexOf('-') > -1))
        {
            e.Handled = true;
        }
    }

【问题讨论】:

  • 为什么不使用 NumericUpDown 控件?它是为数字设计的,可用于负数。

标签: c# visual-studio winforms textbox


【解决方案1】:

您可以使用SelectionStart检查光标所在的位置:

var textBox = (TextBox)sender;

if (e.KeyChar == '-' && (textBox.SelectionStart !=0 || textBox.Text.Contains("-"))) 
{
  e.Handled = true;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    相关资源
    最近更新 更多