键入时如何在文本框C#中设置1 000 000或25 000的格式?
我想在键入时格式化文本框的内容。我知道我可以在LostFocus事件中执行此操作,但我希望在键入时执行此操作。有人对如何实施这一点有什么建议吗? 示例文本框Windows计算器键入时如何在文本框C#中设置1 000 000或25 000的格式?,c#,.net,winforms,C#,.net,Winforms,我想在键入时格式化文本框的内容。我知道我可以在LostFocus事件中执行此操作,但我希望在键入时执行此操作。有人对如何实施这一点有什么建议吗? 示例文本框Windows计算器 每次击键都会触发Keypress事件,因此您可以将格式化代码放入该事件处理程序中,以确保对文本框的任何更改都会运行格式化代码public void textBox1\u Keypress(object sender,System.Windows.Forms.KeyPressEventArgs e) public voi
每次击键都会触发Keypress事件,因此您可以将格式化代码放入该事件处理程序中,以确保对文本框的任何更改都会运行格式化代码
public void textBox1\u Keypress(object sender,System.Windows.Forms.KeyPressEventArgs e)
public void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if ((int)(e.KeyChar) != 8)
{
if ((((int)(e.KeyChar) < 48 | (int)(e.KeyChar) > 57) & (int)(e.KeyChar) != 46) | ((int)(e.KeyChar) == 46 & textBox1.Text.Contains(".")))
{
e.Handled = true;
}
else
{
if (!textBox1.Text.Contains("."))
{
int iLength = textBox1.Text.Replace(",", "").Length;
if (iLength % 3 == 0 & iLength > 0)
{
if ((int)(e.KeyChar) != 46)
{
textBox1.AppendText(",");
}
}
}
}
}
else
{
if (textBox1.Text.LastIndexOf(",") == textBox1.Text.Length - 2 & textBox1.Text.LastIndexOf(",") != -1)
{
textBox1.Text = textBox1.Text.Remove(textBox1.Text.LastIndexOf(","), 1);
textBox1.SelectionStart = textBox1.Text.Length;
}
}
}
{
如果((int)(e.KeyChar)!=8)
{
如果(((int)(e.KeyChar)<48 |(int)(e.KeyChar)>57)和(int)(e.KeyChar)!=46)|((int)(e.KeyChar)==46&textBox1.Text.Contains(“.”))
{
e、 已处理=正确;
}
其他的
{
如果(!textBox1.Text.Contains(“.”)
{
int-iLength=textBox1.Text.Replace(“,”,“).Length;
如果(iLength%3==0&iLength>0)
{
如果((int)(e.KeyChar)!=46)
{
textBox1.附录文本(“,”);
}
}
}
}
}
其他的
{
if(textBox1.Text.LastIndexOf(“,”)==textBox1.Text.Length-2&textBox1.Text.LastIndexOf(“,”)=1)
{
textBox1.Text=textBox1.Text.Remove(textBox1.Text.LastIndexOf(“,”,1);
textBox1.SelectionStart=textBox1.Text.Length;
}
}
}
在键盘类型事件期间:
- 将键入的文本解析为整数并存储值,例如:
int theinteger
- 用
string.Format(“{0:n0}”,integer)重写回
代码>textbox.Text