仅数字,点和退格键. [英] Only number, dot, and backspace.

查看:95
本文介绍了仅数字,点和退格键.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这个问题确实很容易,但是我仍然找不到它.

我当前的文本框具有接受数字和退格键的功能.
但是输入必须是一个浮动variabel,这意味着我也需要点(逗号?).

I think this question is really easy, but nonetheless, i coulnd''t find it.

My current textbox has the ability to accept numbers, and backspace.
But the input has to be a float variabel, whitch means that i''ll need dots (comma''s?) as well.

private void tb_Stash_KeyPress(object sender, KeyPressEventArgs e)
{
  if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
    e.Handled = true; 
}


推荐答案

使用扩展方法进行适当的比较:

Make an extension method that does the appropriate comparison:

public static class ExtensionMethods
{
    public static bool IsCharacter(this char c, char thatChar)
    {
        return (c == thatChar);
    }
}



并这样称呼:



And call it this way:

e.Handled = (!char.IsDigit(e.KeyChar)   && 
             !char.IsControl(e.KeyChar) && 
             !char.IsCharacter(System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator.GetAt(0)));



如果您愿意,也可以考虑使用CurrencyGroupSeparator.



If you want to, you can also account for the CurrencyGroupSeparator.


对于任何一种文化(.''或",),这样的事情都会对您有所帮助. :

Something like this would do it for you for any kind of culture (''.'' or '',''):

private void tb_Stash_KeyPress(object sender, KeyPressEventArgs e)
{
  System.Globalization.CultureInfo c = System.Globalization.CultureInfo.CurrentUICulture;
  char dot = (char)c.NumberFormat.NumberDecimalSeparator[0];
  if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar) && !e.KeyChar.Equals(dot))
    e.Handled = true;
}


您可以使用另一种方法,该方法因地区而异,可以更轻松地更改需求.尝试使用Double.TryParse(...)解析输入到TextBox中的内容,并仅在解析成功时才接受输入:

You could use a different approach that will be more lenient to changing requirements due to locale. Try to parse what has been input into the TextBox with Double.TryParse(...) and accept the input only when parsing was successfull:

private void tb_Stash_KeyPress(object sender, KeyPressEventArgs e)
{
    String alreadyInput = tb_Stash.Text;
    String wouldBe      = alreadyInput + e.KeyChar;
    Double shouldBe;
    if(!Double.TryParse(wouldBe, out shouldBe))
    {
        e.Handled = true;
    }
    else
    {
        //You could do something with shouldBe here if you wanted
    }
}



最好的问候,



Best Regards,


这篇关于仅数字,点和退格键.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆