日期:2014-05-18  浏览次数:20961 次

自定义 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)
{