c# - 文本框验证是否允许一个“。 ”值C#

标签 c# .net winforms textbox

我希望文本框验证仅允许一个.值和一个数字。表示我的文本框值应仅包含数字和一个.值。值应类似于123.50。
我正在使用代码在值的末尾添加.oo.50值。
我的代码是

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


它占用了键盘上的所有键,但是我只想取数字和一个.值。

最佳答案

为您的文本框添加Control.KeyPress事件处理程序。

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;
    }
}


您可以通过设计器或在构造函数中进行如下操作:

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


我还添加了几项检查,以确保您不仅可以在文本末尾插入数字,而且可以在任何位置插入数字。同样带点。它控制您在点右边的位数不超过2位。我已经使用TextBox.SelectionStart Property来获取光标在文本框中的位置。检查此线程以获取有关此信息的更多信息:How do I find the position of a cursor in a text box?

关于c# - 文本框验证是否允许一个“。 ”值C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13774890/

相关文章:

c# - 如何正确更新我的图表值? (实时)

c# - 身份服务器 4 : Sorry, 出现错误:unauthorized_client

c# - 限制单次执行一个方法的线程数

C#- 新手的控制台程序创意

c# - 如何绑定(bind)到 Style.Resource 中的附加属性?

c# - 在 DDD 中管理持久性

winforms - 未从 Vista 中的 machine.config 读取 appSettings

c# - GZip header 中的魔数(Magic Number)不正确。确保您传入的是 GZip 流。(.exe 文件)

c# - 复制到 Dropbox 文件夹时修改 LastWriteTime

c# - 用 Roslyn 为某个方法的调用者提供信息