Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在屏蔽文本框中防止两个连续的逗号_C#_Regex_Winforms_Textbox - Fatal编程技术网

C# 在屏蔽文本框中防止两个连续的逗号

C# 在屏蔽文本框中防止两个连续的逗号,c#,regex,winforms,textbox,C#,Regex,Winforms,Textbox,我有一个带面具的文本框。我只允许用户输入数值和逗号 如果用户连续输入两个逗号,如,,我想删除最后一个逗号 用户只需输入1个逗号 例如: TextBox值为100,00如果用户像100,00,00那样输入此值,我想将其更改为100,00,00 如果在按键事件中连续输入了两个逗号,如何删除第二个逗号?请尝试以下操作: private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsC

我有一个带面具的文本框。我只允许用户输入数值和逗号

如果用户连续输入两个逗号,如
,我想删除最后一个逗号

用户只需输入1个逗号

例如:

TextBox
值为
100,00
如果用户像
100,00,00
那样输入此值,我想将其更改为
100,00,00

如果在
按键
事件中连续输入了两个逗号,如何删除第二个逗号?

请尝试以下操作:

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

当您要使用字符串时,是否可以对其执行
替换(“,”,“,”)
?否则,请使用一些逻辑来跟踪上次输入的字符。如果(e.KeyChar==','&&maskedTextBox1.Text.EndsWith(“,”),我需要在按键事件
上使用它。您的
MaskedTextBox
的掩码格式是什么?您不需要“删除”第二个逗号,只需阻止它被输入即可。见下面我的答案。
int sequenceCount = 0;
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == ',')
        sequenceCount++;
    else
        sequenceCount = 0;

    if ((!char.IsControl(e.KeyChar)
    && !char.IsDigit(e.KeyChar)
    && e.KeyChar != ',') ||  sequenceCount>1)
    {
        e.Handled = true;
    }
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    // you might also want to check if the textBox1 is empty or whatever else. 
    if (e.KeyChar == ',' && textBox1.Text.EndsWith(",")) 
    {
        e.Handled = true;
    }
}