簡體   English   中英

自動格式化文本框文本

[英]Auto formatting a textbox text

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

如果用戶輸入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!

如果只讓用戶鍵入然后在用戶離開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;

}

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

我用了

    int amount;
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        amount++;
        if (amount == 2)
        {
            textBox1.Text += " ";
            textBox1.Select(textBox1.Text.Length, 0);
            amount = 0;
        }
    }

在TextChanged事件上嘗試此

textBoxX3.Text = Convert.ToInt64(textBoxX3.Text.Replace(",", "")).ToString("N0");
textBoxX3.SelectionStart = textBoxX3.Text.Length + 1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM