【C#】文本框中只允许输入数字(含小数点、负号)控制源码
				
									
					
					
						|  | 
							admin 2024年10月16日 17:20
								本文热度 2177 | 
					
				 
				【C#】文本框中只允许输入数字(含小数点、负号)控制源码源码控制
private void tbxScores_KeyPress(object sender, KeyPressEventArgs e)
{
    // 允许退格键(Backspace)  
    if (e.KeyChar == (char)Keys.Back)
    {
        e.Handled = false;
        return;
    }
 
    // 允许小数点,但仅限于一次,并且不能在已经有小数点的情况下再输入  
    if (e.KeyChar == '.')
    {
        if (!tbxScores.Text.Contains("."))
        {
            e.Handled = false;
            return;
        }
        else
        {
            e.Handled = true;
            return;
        }
    }
 
    // 允许负号,但仅限于文本框为空或当前第一个字符是负号  
    if (e.KeyChar == '-')
    {
        if (tbxScores.Text.Length == 0 || (tbxScores.Text.Length > 0 && tbxScores.Text[0] == '-'))
        {
            e.Handled = false;
            return;
        }
        else
        {
            e.Handled = true;
            return;
        }
    }
 
    // 允许数字  
    if (char.IsDigit(e.KeyChar))
    {
        e.Handled = false;
        return;
    }
 
    // 阻止其他所有按键  
    e.Handled = true;
}
该文章在 2024/10/17 12:05:27 编辑过