0

我想在用户将值输入文本框时更改文本。

这边走:

1 = 1
12 = (12) 
123 = (12) 3
1234 = (12) 34

我做了这个代码:

private void txtFoneres_KeyDown(object sender, KeyEventArgs e)
{
    string p1 = e.KeyData.ToString();
    if (p1.StartsWith("D"))
    {
        p1 = p1.Replace("D", "");
    }
    if (p1.StartsWith("NumPad"))
    {
        p1 = p1.Replace("NumPad", "");
    }

    if (txtFoneres.TextLength == 1)
    {

        txtFoneres.Text = txtFoneres.Text + "(" + p1 + ")";
        txtFoneres.SelectionStart = 2;
        txtFoneres.SelectionLength = 2;
    }
}

使用我的代码,结果如下:

"1" = "1 
"12" = "1(2" (this is the problem, it would have to start with "("

有谁知道如何解决它并将1(2)更改为(12)?

4

1 回答 1

0

我会尝试使用 带有一行代码的MaskedTextBox

private void maskedTextBox1_KeyUp(object sender, KeyEventArgs e)
{
    if (maskedTextBox1.Text.Length == 1)
    {
        maskedTextBox1.Mask = "(00) 00";
        maskedTextBox1.SelectionStart = 2;
    }
}
于 2013-04-14T04:00:56.440 回答