自定义 Textbox?
下面的代码自定义了一个输入数字的textbox控件,我想如何能在输入111后自动在后面追加一个‘,’呢?注意是在输入完第三个1后自动追加。
下面的代码怎么修改?3KS
[code=C#][/code]
public class NumericTextBox : TextBox
{
bool allowSpace = false;
// Restricts the entry of characters to digits (including hex), the negative sign,
// the decimal point, and editing keystrokes (backspace).
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
NumberFormatInfo numberFormatInfo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat;
string decimalSeparator = numberFormatInfo.NumberDecimalSeparator;
string groupSeparator = numberFormatInfo.NumberGroupSeparator;
string negativeSign = numberFormatInfo.NegativeSign;
string keyInput = e.KeyChar.ToString();
if (Char.IsDigit(e.KeyChar))
{
// Digits are OK
}
else if (keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator) ||
keyInput.Equals(negativeSign))
{
// Decimal separator is OK
}
else if (e.KeyChar == '\b')
{
// Backspace key is OK
}
// else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0)
// {
// // Let the edit control handle control and alt key combinations
// }
else if (this.allowSpace && e.KeyChar == ' ')
{
}
else
{
// Swallow this invalid key and beep
e.Handled = true;
// MessageBeep();
}
}
public int IntValue
{
get
{
return Int32.Parse(this.Text);
}
}
public decimal DecimalValue
{
get
{
return Decimal.Parse(this.Text);
}
}
public bool AllowSpace
{
set
{
this.allowSpace = value;
}
get
{
return this.allowSpace;
}
}
}
[解决办法]
不好意思,我不太喜欢看别人写的代码,因为你的思路我不太清楚,但是你目的我明白了,就是要在文本框中输入完"111"后,文本框中的内容变成"111,"(不含引号),我加了个函数,不知道行不行,我已经试过了,在我的机子上是行的,代码如下:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == "111") textBox1.Text = textBox1.Text + ","; \\就是捕捉一个文本框内容改变事件
}
[解决办法]
先在类里添加一个字段,int press = 0;用来临时保存按1的次数
在你的OnKeyPress里的if (Char.IsDigit(e.KeyChar))段里添加一段
if (e.KeyChar == '1')
{
press++;
}
else if( e.KeyChar != '1' )
{
press = 0;
}
然后添加一个重载
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp (e);
if( press == 3 )
{
int start = this.SelectionStart; // 定义光标的位置,不然this.Text += ","后光标回到第一个位置
this.Text += ",";
press = 0;
this.SelectionStart = start + 1;
}
}
[解决办法]
关于解决这个问题我的一种另想法,共ls参考
1. 当用户输入新的字符时(OnKeyPress事件),获取所有文本框内字符串,用string.Replace(",","")获取去掉的","字符串。如200,000被转换成200000。
2. 用decimal.TryParse()判断是否是合法的数字字符串。
3.使用string.format("N")出格式化字符串,然后把它填充回这个文本框。
[解决办法]
提个思路,判断textbox上的字符去“,”后的长度!当其能被3整除时,加个“,”。