文本框验证允许一个" 。 "值c#文本框、QUOT

2023-09-06 16:40:02 作者:白衣不染尘

我想文本框验证只允许有一个价值,只有编号。意味着我的文本框的值应该只有数字和一个值。价值应该是这样的123.50。 我使用的是code在我的价值的末尾添加 .oo 0.50 值。 我的code是

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");

这是考虑到键盘的所有按键,但我想利用数字和一个值。

推荐答案

添加的 Control.Key preSS 的事件处理程序的文本框。

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地产让光标在文本框中的位置。检查此线程有关的详细信息:How我觉得光标在一个文本框的位置?

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?