我想自动格式化在文本框中输入的文本,如下所示:
如果用户输入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!
答案 0 :(得分: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;
}
答案 1 :(得分: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;
}
}
答案 2 :(得分: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;
}
}
答案 3 :(得分:0)
试试这个.. 在TextChanged事件
textBoxX3.Text = Convert.ToInt64(textBoxX3.Text.Replace(",", "")).ToString("N0");
textBoxX3.SelectionStart = textBoxX3.Text.Length + 1;