允许一个“文本框验证"."价值 c# [英] textbox validation for allow one " . " value c#

查看:18
本文介绍了允许一个“文本框验证"."价值 c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望文本框验证只允许一个 . 值和数字.意味着我的文本框值应该只采用数字和一个 . 值.值应该是 123.50.我正在使用代码在我的值末尾添加 .oo.50 值.我的代码是

I want textbox validation for allowing only one . value and only numbers. Means my textbox value should take only numerics and one . value. Value should be like 123.50. I am using a code for adding .oo or .50 value at end of my value. My code is

double x;
double.TryParse(tb.Text, out x);
tb.Text = x.ToString(".00");

它从键盘上获取所有键,但我只想获取数字和一个 . 值.

It is taking all the keys from keyboard, but I want to take only numbers and one . value.

推荐答案

添加一个Control.KeyPress 文本框的事件处理程序.

Add a Control.KeyPress event handler for your textbox.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar))  //bypass control keys
    {
        int dotIndex = textBox1.Text.IndexOf('.');
        if (char.IsDigit(e.KeyChar))     //ensure it's a digit
        {   //we cannot accept another digit if
            if (dotIndex != -1 &&  //there is already a dot and
                //dot is to the left from the cursor position and
                dotIndex < textBox1.SelectionStart &&
                //there're already 2 symbols to the right from the dot
                textBox1.Text.Substring(dotIndex + 1).Length >= 2)
            {
                e.Handled = true;
            }
        }
        else //we cannot accept this char if
            e.Handled = e.KeyChar != '.' || //it's not a dot or
                        //there is already a dot in the text or
                        dotIndex != -1 ||   
                        //text is empty or
                        textBox1.Text.Length == 0 || 
                        //there are more than 2 symbols from cursor position
                        //to the end of the text
                        textBox1.SelectionStart + 2 < textBox1.Text.Length;
    }
}

您可以通过设计器或在您的构造函数中这样做:

You may do it through designer or in your constructor like this:

public Form1()
{
    InitializeComponent();
    //..other initialization
    textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
}

我还添加了几项检查以确保您不仅可以在文本末尾插入数字,还可以在任何位置插入数字.与点相同.它控制您从点右侧不超过 2 位数字.我用过 TextBox.SelectionStart 属性 获取光标在文本框中的位置.检查此线程以获取更多信息:如何在文本框中找到光标的位置?

I have also added several checks to ensure, that you could insert digits not only in the end of the text, but in any position. Same with a dot. It controls that you have not more than 2 digits to the right from the dot. I've used TextBox.SelectionStart Property to get the position of the cursor in the textbox. Check this thread for more info about that: How do I find the position of a cursor in a text box?

这篇关于允许一个“文本框验证"."价值 c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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