How to insert hyphen “-” after 2 digits automatically in TextBox?

血红的双手。 提交于 2020-07-22 21:36:02

问题


I have one TextBox for user to input number.

When user input to the TextBox then the format should be like this

01-22-34-40-33

I want to insert "-" after 2 digits in the TextChanged event handler.

I do something like this but no work:

if(txtRandomThirdTypeSales.Text.Length == 2)
{
    txtRandomThirdTypeSales.Text += "-";
}
else if (txtRandomThirdTypeSales.Text.Length == 5)
{
    txtRandomThirdTypeSales.Text += "-";        
}
else if (txtRandomThirdTypeSales.Text.Length == 8)
{
    txtRandomThirdTypeSales.Text += "-";        
}
else if (txtRandomThirdTypeSales.Text.Length == 11)
{
    txtRandomThirdTypeSales.Text += "-";
}

回答1:


Can you please try this way,this may be will helpful for you.

private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        string sVal = textBox1.Text;

        if (!string.IsNullOrEmpty(sVal) && e.KeyCode != Keys.Back)
        {
            sVal = sVal.Replace("-", "");
            string newst = Regex.Replace(sVal, ".{2}", "$0-");
            textBox1.Text = newst;
            textBox1.SelectionStart = textBox1.Text.Length;
        }
    }

Let me know if you need any help.




回答2:


Maybe you can try this

if(txtRandomThirdTypeSales.Text.Count(x => x != '-') % 2 == 0)
{
    txtRandomThirdTypeSales.Text += "-";
}

That way it counts all the chars that are not a - and checks if they are even. If they are, add the '-'.

You can make it more restrictive by checking that they are digits with a regex. ^\d




回答3:


Can you please try this

if(txtRandomThirdTypeSales.Text.Length % 3 == 2)
{
    txtRandomThirdTypeSales.Text += "-";
}

You can also add code to handle backspace key down and delete key down.




回答4:


Have you tried TextBox masking? it is available in Winform controls

Here is your reference http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx



来源:https://stackoverflow.com/questions/28038145/how-to-insert-hyphen-after-2-digits-automatically-in-textbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!