c# - 如何在TextBox中自动在2位数字后插入连字符 "-"?

标签 c# winforms textbox

我有一个文本框供用户输入数字。

当用户输入到文本框时,格式应该是这样的

01-22-34-40-33

我想在 TextChanged 事件处理程序中的 2 位数字后插入“-”。

我做了这样的事情但没有工作:

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 += "-";
}

最佳答案

你能试试这个方法吗,这可能对你有帮助。

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

如果您需要任何帮助,请告诉我。

关于c# - 如何在TextBox中自动在2位数字后插入连字符 "-"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28038145/

相关文章:

c# - WinForms - 在 TableLayoutPanel 中重叠两个控件

c# - 如何刷新DataGridView单元格样式

c# - 按下按钮后如何使数字出现在文本框中?

c# - ConfigurationManager 没有在 app.config 中保存值

c# - 在任何打开的应用程序的文本字段中获取 'word before the cursor' 的最佳方法

javascript - 在javascript中获取控件的 "id"值

c# - 带有 viewModel 的嵌套局部 View

c# - 设计自定义随机类

c# - 获取 GridView 的列标题的 css

c# - 删除 Grid 的指定子元素