本文介绍了自动格式化文本框文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想自动格式化在文本框中输入的文本,如下所示:
I want to auto format a text entered in a textbox like so:
如果用户输入 2 个字符,例如 38,它会自动添加一个空格.所以,如果我输入 384052最终结果将是:38 30 52.
If a user enters 2 characters, like 38, it automatically adds a space. so, if I type 384052The end result will be: 38 30 52.
我试过这样做,但出于某种原因从右到左,一切都搞砸了..我做错了什么?
I tried doing that, but it's ofr some reason right to left and it's all screwed up.. what I'm doing wrong?
static int Count = 0;
private void packetTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
Count++;
if (Count % 2 == 0)
{
packetTextBox.Text += " ";
}
}
Thanks!
推荐答案
如果你只是让用户输入然后在用户离开 TextBox
时修改内容会更好.
It's much nicer if you just let the user type and then modify the contents when the user leaves the TextBox
.
您可以通过不响应 KeyPress
事件,而是响应 TextChanged
事件来实现.
You can do that by reacting not to the KeyPress
event, but to the TextChanged
event.
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;
}
这篇关于自动格式化文本框文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!