如何编写按键功能的普通功能检查在C#中的文本框的浮动数量? [英] How to write common function for keypress function check for floating number of a textbox in C#?

查看:187
本文介绍了如何编写按键功能的普通功能检查在C#中的文本框的浮动数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为两个以上的文本框调用一个通用函数,这样keypress就可以检查只有浮点数可以输入。

这是我的示例代码:这仅适用于单个文本框( tbL1Distance )。但是我想把它作为一个普通的文本框控件。

pre prerivate $ {private void tbL1Distance_KeyPress(object sender,KeyPressEventArgs e)
{
char ch = e.KeyChar;

if(ch == 46& tbL1Distance.Text.IndexOf('。')!= -1)
{
e.Handled = true;
return; ($!


if(!Char.IsDigit(ch)&& ch!= 8& ch!= 46)
{
e。 Handled = true;




$ b $ p

$你可以简单的创建你自己的控件,继承 TextBox ,你可以重载<$ c

$ p $ public class CustomTextBox:System.Windows.Forms.TextBox
$ b保护覆盖无效OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
{
char ch = e.KeyChar; (ch == 46&& this.Text.IndexOf('。'!!= -1)//用'this'替换'tbL1Distance'来引用当前的TextBox。
{
e.Handled = true;

else if(!Char.IsDigit(ch)&& ch!= 8& ch!= 46)
{
e.Handled = true ;
}
base.OnKeyPress(e);






完成后,转到 Build 菜单,然后按在此处生成<您的项目名称> ,您的控件现在可以在工具箱的顶部找到。现在只需要用你自己的替换每一个正常的 TextBox



如果您不希望在验证失败的情况下触发 KeyPress 事件,您可以添加 return; if -statements中。


I want to call a common function for more than 2 textboxes so that keypress can check that only floating point number can take a input.

This is my sample code: this work only for a single textbox (tbL1Distance). But I want it as a common textbox control.

private void tbL1Distance_KeyPress(object sender, KeyPressEventArgs e)
{
        char ch = e.KeyChar;

        if (ch == 46 && tbL1Distance.Text.IndexOf('.') != -1)
        {
            e.Handled = true;
            return;
        }

        if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
        }
}

Thanks in advance.

解决方案

You can simply create your own control, inheriting the TextBox, where you override the OnKeyPress method.

public class CustomTextBox : System.Windows.Forms.TextBox
{
    protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
    {
        char ch = e.KeyChar;

        if (ch == 46 && this.Text.IndexOf('.') != -1) //Replaced 'tbL1Distance' with 'this' to refer to the current TextBox.
        {
            e.Handled = true;
        }
        else if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
        {
            e.Handled = true;
        }
        base.OnKeyPress(e);
    }
}

When done, go to the Build menu and press Build <your project name here>, and your control can now be found on the top of your Tool Box. Now just replace every normal TextBox with your own.

If you don't want the KeyPress event to be fired at all if your validation fails, you can just add return; in both if-statements.

这篇关于如何编写按键功能的普通功能检查在C#中的文本框的浮动数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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