0

我想自动格式化在文本框中输入的文本,如下所示:

如果用户输入 2 个字符,例如 38,它会自动添加一个空格。所以,如果我输入 384052 最终结果将是:38 30 52。

我试过这样做,但出于某种原因,从右到左,一切都搞砸了..我做错了什么?

static int Count = 0;
     private void packetTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            Count++;
            if (Count % 2 == 0)
            {
                packetTextBox.Text += " ";
            }
        }


Thanks!
4

4 回答 4

1

如果你让用户输入然后在用户离开时修改内容会更好TextBox

您可以通过不对KeyPress事件做出反应,而是对TextChanged事件做出反应来做到这一点。

private void packetTextBox_TextChanged(object sender, EventArgs e)
{
    string oldValue = (sender as TextBox).Text.Trim();
    string newValue = "";

    // IF there are more than 2 characters in oldValue:
    //     Move 2 chars from oldValue to newValue, and add a space to newValue
    //     Remove the first 2 chars from oldValue
    // ELSE
    //     Just append oldValue to newValue
    //     Make oldValue empty
    // REPEAT as long as oldValue is not empty

    (sender as TextBox).Text = newValue;

}
于 2013-09-19T13:37:26.527 回答
0

试试这个.. 在 TextChanged 事件上

textBoxX3.Text = Convert.ToInt64(textBoxX3.Text.Replace(",", "")).ToString("N0");
textBoxX3.SelectionStart = textBoxX3.Text.Length + 1;
于 2014-02-18T17:09:19.443 回答
0

在 TextChanged 事件中:

 int space = 0;
 string finalString =""; 

 for (i = 0; i < txtbox.lenght; i++)
 {
       finalString  = finalString  + string[i];
       space++;
        if (space = 3 )
        {
            finalString  = finalString  + " ";
            space = 0;
        }
 }
于 2013-09-19T13:39:34.277 回答
0

我用了

    int amount;
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        amount++;
        if (amount == 2)
        {
            textBox1.Text += " ";
            textBox1.Select(textBox1.Text.Length, 0);
            amount = 0;
        }
    }
于 2013-09-20T08:22:49.500 回答