怎么让textbox只接受正整数(要最严谨的方法) 本帖最后由 paschen 于 2011-02-20 18:39:06 编辑 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 将它设置为 DataGridViewNumberBoxCell类型,写个方法。 public class DataGridViewNumberBoxCell : DataGridViewTextBoxCell { private int m_decimalLength = 0; private decimal m_maxValue = 0; private string m_formatString = "#,##0"; private static Type defaultEditType = typeof(dgvNumControl); private static Type defaultValueType = typeof(System.Decimal); [DefaultValue(0)] public int DecimalLength { get { return m_decimalLength; } set { if (m_decimalLength != value) { SetDecimalLength(this.RowIndex, value); OnCommonChange(); // Assure that the cell/column gets repainted and autosized if needed } } } [DefaultValue(0)] public decimal MaxValue { get { return m_maxValue; } set { if (m_maxValue != value) { SetMaxValue(this.RowIndex, value); OnCommonChange(); // Assure that the cell/column gets repainted and autosized if needed } } } public string FormatString { get { return m_formatString; } set { if (m_formatString != value) { SetFormatString(this.RowIndex, value); //OnCommonChange(); // Assure that the cell/column gets repainted and autosized if needed } } } protected override void OnEnter(int rowIndex, bool throughMouseClick) { base.OnEnter(rowIndex, throughMouseClick); } /// <summary> /// /// </summary> public DataGridViewNumberBoxCell() { //this.Value = 0; //LibFunc.ToDecimal(this.Value).ToString("#,##0"); //this.Style.Format = "#,##0"; this.Style.Alignment = DataGridViewContentAlignment.MiddleRight; } public override object Clone() { DataGridViewNumberBoxCell dataGridViewCell = base.Clone() as DataGridViewNumberBoxCell; if (dataGridViewCell != null) { dataGridViewCell.DecimalLength = this.DecimalLength; dataGridViewCell.MaxValue = this.MaxValue; dataGridViewCell.FormatString = this.FormatString; } return dataGridViewCell; } internal void SetDecimalLength(int rowIndex, int value) { m_decimalLength = value; if (OwnsEditingControl(rowIndex)) { this.EditingTNumEditBox.DecimalLength = value; } } internal void SetMaxValue(int rowIndex, decimal value) { m_maxValue = value; if (OwnsEditingControl(rowIndex)) { this.EditingTNumEditBox.MaxValue = value; } } internal void SetFormatString(int rowIndex, string value) { m_formatString = value; //if (OwnsEditingControl(rowIndex)) //{ // this.EditingTNumEditBox.FromatString = value; //} } private dgvNumControl EditingTNumEditBox { get { return this.DataGridView.EditingControl as dgvNumControl; } } private bool OwnsEditingControl(int rowIndex) { if (rowIndex == -1 || this.DataGridView == null) { return false; } dgvNumControl editingControl = this.DataGridView.EditingControl as dgvNumControl; return editingControl != null && rowIndex == ((IDataGridViewEditingControl)editingControl).EditingControlRowIndex; } private void OnCommonChange() { if (this.DataGridView != null && !this.DataGridView.IsDisposed && !this.DataGridView.Disposing) { if (this.RowIndex == -1) { this.DataGridView.InvalidateColumn(this.ColumnIndex); } else { this.DataGridView.UpdateCellValue(this.ColumnIndex, this.RowIndex); } } } public override Type EditType { get { return defaultEditType; } } public override Type ValueType { get { Type valueType = base.ValueType; if (valueType != null) { return valueType; } return defaultValueType; } } public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle) { base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle); UbNumBox numEditBox = this.DataGridView.EditingControl as UbNumBox; if (numEditBox != null) { numEditBox.BorderStyle = BorderStyle.None; numEditBox.DecimalLength = this.DecimalLength; numEditBox.MaxValue = this.MaxValue; numEditBox.FromatString = this.FormatString; //numEditBox.AllowNegative = this.AllowNegative; string initialFormattedValueStr = initialFormattedValue as string; if (string.IsNullOrEmpty(initialFormattedValueStr)) { numEditBox.Text = ""; } else { numEditBox.Text = LibFunc.ToDecimal(initialFormattedValueStr).ToString(FormatString); } } } [EditorBrowsable(EditorBrowsableState.Advanced)] public override void DetachEditingControl() { DataGridView dataGridView = this.DataGridView; if (dataGridView == null || dataGridView.EditingControl == null) { throw new InvalidOperationException("Cell is detached or its grid has no editing control."); } UbNumBox numEditBox = dataGridView.EditingControl as UbNumBox; if (numEditBox != null) { numEditBox.ClearUndo(); // avoid interferences between the editing sessions } base.DetachEditingControl(); } /// <summary> /// GridView中的NumberBox变色 /// </summary> /// <param name="graphics"></param> /// <param name="clipBounds"></param> /// <param name="cellBounds"></param> /// <param name="rowIndex"></param> /// <param name="elementState"></param> /// <param name="value"></param> /// <param name="formattedValue"></param> /// <param name="errorText"></param> /// <param name="cellStyle"></param> /// <param name="advancedBorderStyle"></param> /// <param name="paintParts"></param> protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates elementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { //可写的时候,单元格变黄色 if (!this.ReadOnly) { cellStyle.BackColor = Color.Yellow; } base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts); } } WndProc中屏蔽复制http://topic.csdn.net/t/20061222/15/5249512.html http://blog.csdn.net/wuyazhe/archive/2010/07/12/5729338.aspx稍微修改一点。public class IntegerTextbox : TextBox{ protected override void OnKeyPress(KeyPressEventArgs e) { e.Handled = !(Char.IsNumber(e.KeyChar) || e.KeyChar == (char)8); if (!e.Handled) this.Tag = this.Text;//记录最后一次正确输入 base.OnKeyPress(e); } protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); if (!System.Text.RegularExpressions.Regex.IsMatch((this).Text, @"^(?!0\d)\d*$")) { int index = (this).SelectionStart; (this).Text = (this).Tag as string; (this).SelectionStart = index; } } public const int WM_PASTE = 0x302; protected override void WndProc(ref Message m) { if (m.Msg == WM_PASTE)//粘贴 { if (!System.Text.RegularExpressions.Regex.IsMatch(Clipboard.GetText(), @"^(?!0\d)\d*$")) return; } base.WndProc(ref m); }}如果你允许输入00的情况。可以修改为public class IntegerTextbox : TextBox{ protected override void OnKeyPress(KeyPressEventArgs e) { e.Handled = !(Char.IsNumber(e.KeyChar) || e.KeyChar == (char)8); if (!e.Handled) this.Tag = this.Text;//记录最后一次正确输入 base.OnKeyPress(e); } protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); if (!System.Text.RegularExpressions.Regex.IsMatch((this).Text, @"^\d*$")) { int index = (this).SelectionStart; (this).Text = (this).Tag as string; (this).SelectionStart = index; } } public const int WM_PASTE = 0x302; protected override void WndProc(ref Message m) { if (m.Msg == WM_PASTE)//粘贴 { if (!System.Text.RegularExpressions.Regex.IsMatch(Clipboard.GetText(), @"^\d*$")) return; } base.WndProc(ref m); }} 用你的第二种方法.. 光标搞到最后 private int tempStr; private void textBox1_TextChanged(object sender, EventArgs e) { if (Regex.IsMatch(textBox1.Text, @"^\d+$") == false) { textBox1.Text = tempStr.ToString(); this.textBox1.SelectionStart = this.textBox1.TextLength; // 设置光标最后显示 } else { tempStr = Convert.ToInt32(textBox1.Text); } } 用你的第二种方法.. 光标搞到最后 [code=C] private int tempStr; private void textBox1_TextChanged(object sender, EventArgs e) { if (Regex.IsMatch(textBox1.Text, @"^\d+$") == false) { textBox1.Text = tempStr.ToString(); this.textBox1.SelectionStart = this.textBox1.TextLength; // 设置光标最后显示 } else { tempStr = Convert.ToInt32(textBox1.Text); } } [/code] 用你的第二种方法.. 光标搞到最后 private int tempStr; private void textBox1_TextChanged(object sender, EventArgs e) { if (Regex.IsMatch(textBox1.Text, @"^\d+$") == false) { textBox1.Text = tempStr.ToString(); this.textBox1.SelectionStart = this.textBox1.TextLength; // 设置光标最后显示 } else { tempStr = Convert.ToInt32(textBox1.Text); } } 各位大哥,我有个几个问题请教你们;楼主那个方法一的e.KeyChar != 8是什么意思?e.KeyChar = Convert .ToChar (0);能有什么作用?还有你那个方法二和方法三中Regex我在控制台应用程序怎么点不出来? 感觉还是在WndProc里面过滤一下的好:class myTxt : System.Windows.Forms.TextBox { protected override void WndProc(ref System.Windows.Forms.Message m) { if(m.Msg == 0x0102) //WM_CHAR { switch (m.WParam.ToInt32()) { case 8: //退格 case 13: //回车 case 46: //删除 base.WndProc(ref m); return; } if (m.WParam.ToInt32() < 48 || m.WParam.ToInt32() > 57) return; } if (m.Msg == 0x0302) //WM_PASTE return; base.WndProc(ref m); } }然后在你的Form里面定义:private myTxt textBox1;this.textBox1 = new WindowsFormsApplication1.myTxt();this.textBox1.Location = new System.Drawing.Point(xx, yy);this.textBox1.Name = "textBox1";this.textBox1.Size = new System.Drawing.Size(xx, yy);this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress); <script type="text/javascript"> function clearNoNum(obj) { //先把非数字的都替换掉,除了数字和. obj.value = obj.value.replace(/[^\d.]/g,""); //必须保证第一个为数字而不是. obj.value = obj.value.replace(/^\./g,""); //保证只有出现一个.而没有多个. obj.value = obj.value.replace(/\.{2,}/g,"."); //保证.只出现一次,而不能出现两次以上 obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$","."); } </script>//Textbox 如下:<asp:TextBox ID="TextBox5" Width="60px" onkeyup='clearNoNum(this)' runat="server"></asp:TextBox> 最严谨最高效最节省代码的方法:拖一个NumericUpDown控件进去,设置它的Minimun的最小值是0,increment为1即可。 我就很奇怪啊,这么个简单的问题让各位高手的代码写了这么长?难道我out了? Form接收条码扫描器扫描到的条码,怎样显示出来 未将对象引用设置到对象的实例 一个新手的问题,望能帮忙指点一下.. [求助]动态数组ArrayList的问题 怎样禁止一台计算机上网? 控件之间相互调用传值 怎么在picturebox里面移动画的点 在c#怎么使用组件? c#.net下将SQL Server数据库文件导出为.txt格式 高手请指点迷津(急) 怎么将TXT的每一列分别写入到不同的txt中 C#中Attribute属性,Attribute属性
public class DataGridViewNumberBoxCell : DataGridViewTextBoxCell
{
private int m_decimalLength = 0;
private decimal m_maxValue = 0;
private string m_formatString = "#,##0";
private static Type defaultEditType = typeof(dgvNumControl);
private static Type defaultValueType = typeof(System.Decimal); [DefaultValue(0)]
public int DecimalLength
{
get { return m_decimalLength; }
set
{
if (m_decimalLength != value)
{
SetDecimalLength(this.RowIndex, value);
OnCommonChange(); // Assure that the cell/column gets repainted and autosized if needed
}
}
} [DefaultValue(0)]
public decimal MaxValue
{
get { return m_maxValue; }
set
{
if (m_maxValue != value)
{
SetMaxValue(this.RowIndex, value);
OnCommonChange(); // Assure that the cell/column gets repainted and autosized if needed
}
}
} public string FormatString
{
get { return m_formatString; }
set
{
if (m_formatString != value)
{
SetFormatString(this.RowIndex, value);
//OnCommonChange(); // Assure that the cell/column gets repainted and autosized if needed
}
}
} protected override void OnEnter(int rowIndex, bool throughMouseClick)
{
base.OnEnter(rowIndex, throughMouseClick);
} /// <summary>
///
/// </summary>
public DataGridViewNumberBoxCell()
{
//this.Value = 0;
//LibFunc.ToDecimal(this.Value).ToString("#,##0");
//this.Style.Format = "#,##0";
this.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
} public override object Clone()
{
DataGridViewNumberBoxCell dataGridViewCell = base.Clone() as DataGridViewNumberBoxCell;
if (dataGridViewCell != null)
{
dataGridViewCell.DecimalLength = this.DecimalLength;
dataGridViewCell.MaxValue = this.MaxValue;
dataGridViewCell.FormatString = this.FormatString;
}
return dataGridViewCell;
} internal void SetDecimalLength(int rowIndex, int value)
{
m_decimalLength = value;
if (OwnsEditingControl(rowIndex))
{
this.EditingTNumEditBox.DecimalLength = value;
}
} internal void SetMaxValue(int rowIndex, decimal value)
{
m_maxValue = value;
if (OwnsEditingControl(rowIndex))
{
this.EditingTNumEditBox.MaxValue = value;
}
} internal void SetFormatString(int rowIndex, string value)
{
m_formatString = value;
//if (OwnsEditingControl(rowIndex))
//{
// this.EditingTNumEditBox.FromatString = value;
//}
} private dgvNumControl EditingTNumEditBox
{
get
{
return this.DataGridView.EditingControl as dgvNumControl;
}
} private bool OwnsEditingControl(int rowIndex)
{
if (rowIndex == -1 || this.DataGridView == null)
{
return false;
}
dgvNumControl editingControl = this.DataGridView.EditingControl as dgvNumControl;
return editingControl != null && rowIndex == ((IDataGridViewEditingControl)editingControl).EditingControlRowIndex;
} private void OnCommonChange()
{
if (this.DataGridView != null && !this.DataGridView.IsDisposed && !this.DataGridView.Disposing)
{
if (this.RowIndex == -1)
{
this.DataGridView.InvalidateColumn(this.ColumnIndex);
}
else
{
this.DataGridView.UpdateCellValue(this.ColumnIndex, this.RowIndex);
}
}
} public override Type EditType
{
get { return defaultEditType; }
} public override Type ValueType
{
get
{
Type valueType = base.ValueType;
if (valueType != null)
{
return valueType;
}
return defaultValueType;
}
} public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
{
base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);
UbNumBox numEditBox = this.DataGridView.EditingControl as UbNumBox;
if (numEditBox != null)
{
numEditBox.BorderStyle = BorderStyle.None;
numEditBox.DecimalLength = this.DecimalLength;
numEditBox.MaxValue = this.MaxValue;
numEditBox.FromatString = this.FormatString;
//numEditBox.AllowNegative = this.AllowNegative; string initialFormattedValueStr = initialFormattedValue as string; if (string.IsNullOrEmpty(initialFormattedValueStr))
{
numEditBox.Text = "";
}
else
{
numEditBox.Text = LibFunc.ToDecimal(initialFormattedValueStr).ToString(FormatString);
}
}
} [EditorBrowsable(EditorBrowsableState.Advanced)]
public override void DetachEditingControl()
{
DataGridView dataGridView = this.DataGridView;
if (dataGridView == null || dataGridView.EditingControl == null)
{
throw new InvalidOperationException("Cell is detached or its grid has no editing control.");
} UbNumBox numEditBox = dataGridView.EditingControl as UbNumBox;
if (numEditBox != null)
{
numEditBox.ClearUndo(); // avoid interferences between the editing sessions
} base.DetachEditingControl();
} /// <summary>
/// GridView中的NumberBox变色
/// </summary>
/// <param name="graphics"></param>
/// <param name="clipBounds"></param>
/// <param name="cellBounds"></param>
/// <param name="rowIndex"></param>
/// <param name="elementState"></param>
/// <param name="value"></param>
/// <param name="formattedValue"></param>
/// <param name="errorText"></param>
/// <param name="cellStyle"></param>
/// <param name="advancedBorderStyle"></param>
/// <param name="paintParts"></param>
protected override void Paint(Graphics graphics,
Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
DataGridViewElementStates elementState, object value,
object formattedValue, string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
//可写的时候,单元格变黄色
if (!this.ReadOnly)
{
cellStyle.BackColor = Color.Yellow;
}
base.Paint(graphics, clipBounds, cellBounds, rowIndex,
elementState, value, formattedValue, errorText,
cellStyle, advancedBorderStyle, paintParts);
}
}
http://topic.csdn.net/t/20061222/15/5249512.html
稍微修改一点。
public class IntegerTextbox : TextBox
{
protected override void OnKeyPress(KeyPressEventArgs e)
{
e.Handled = !(Char.IsNumber(e.KeyChar) || e.KeyChar == (char)8);
if (!e.Handled) this.Tag = this.Text;//记录最后一次正确输入
base.OnKeyPress(e);
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
if (!System.Text.RegularExpressions.Regex.IsMatch((this).Text, @"^(?!0\d)\d*$"))
{
int index = (this).SelectionStart;
(this).Text = (this).Tag as string;
(this).SelectionStart = index;
}
}
public const int WM_PASTE = 0x302;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_PASTE)//粘贴
{
if (!System.Text.RegularExpressions.Regex.IsMatch(Clipboard.GetText(), @"^(?!0\d)\d*$")) return;
}
base.WndProc(ref m);
}
}如果你允许输入00的情况。可以修改为public class IntegerTextbox : TextBox
{
protected override void OnKeyPress(KeyPressEventArgs e)
{
e.Handled = !(Char.IsNumber(e.KeyChar) || e.KeyChar == (char)8);
if (!e.Handled) this.Tag = this.Text;//记录最后一次正确输入
base.OnKeyPress(e);
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
if (!System.Text.RegularExpressions.Regex.IsMatch((this).Text, @"^\d*$"))
{
int index = (this).SelectionStart;
(this).Text = (this).Tag as string;
(this).SelectionStart = index;
}
}
public const int WM_PASTE = 0x302;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_PASTE)//粘贴
{
if (!System.Text.RegularExpressions.Regex.IsMatch(Clipboard.GetText(), @"^\d*$")) return;
}
base.WndProc(ref m);
}
}
private int tempStr;
private void textBox1_TextChanged(object sender, EventArgs e)
{ if (Regex.IsMatch(textBox1.Text, @"^\d+$") == false)
{
textBox1.Text = tempStr.ToString();
this.textBox1.SelectionStart = this.textBox1.TextLength; // 设置光标最后显示
}
else
{
tempStr = Convert.ToInt32(textBox1.Text); } }
用你的第二种方法.. 光标搞到最后
[code=C]
private int tempStr;
private void textBox1_TextChanged(object sender, EventArgs e)
{ if (Regex.IsMatch(textBox1.Text, @"^\d+$") == false)
{
textBox1.Text = tempStr.ToString();
this.textBox1.SelectionStart = this.textBox1.TextLength; // 设置光标最后显示
}
else
{
tempStr = Convert.ToInt32(textBox1.Text); } }
[/code]
用你的第二种方法.. 光标搞到最后
private int tempStr;
private void textBox1_TextChanged(object sender, EventArgs e)
{ if (Regex.IsMatch(textBox1.Text, @"^\d+$") == false)
{
textBox1.Text = tempStr.ToString();
this.textBox1.SelectionStart = this.textBox1.TextLength; // 设置光标最后显示
}
else
{
tempStr = Convert.ToInt32(textBox1.Text); } }
楼主那个方法一的e.KeyChar != 8是什么意思?
e.KeyChar = Convert .ToChar (0);能有什么作用?
还有你那个方法二和方法三中Regex我在控制台应用程序怎么点不出来?
class myTxt : System.Windows.Forms.TextBox
{
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if(m.Msg == 0x0102) //WM_CHAR
{
switch (m.WParam.ToInt32())
{
case 8: //退格
case 13: //回车
case 46: //删除
base.WndProc(ref m);
return;
}
if (m.WParam.ToInt32() < 48 || m.WParam.ToInt32() > 57)
return;
}
if (m.Msg == 0x0302) //WM_PASTE
return;
base.WndProc(ref m);
}
}
然后在你的Form里面定义:
private myTxt textBox1;
this.textBox1 = new WindowsFormsApplication1.myTxt();
this.textBox1.Location = new System.Drawing.Point(xx, yy);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(xx, yy);
this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);
function clearNoNum(obj)
{
//先把非数字的都替换掉,除了数字和.
obj.value = obj.value.replace(/[^\d.]/g,"");
//必须保证第一个为数字而不是.
obj.value = obj.value.replace(/^\./g,"");
//保证只有出现一个.而没有多个.
obj.value = obj.value.replace(/\.{2,}/g,".");
//保证.只出现一次,而不能出现两次以上
obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
}
</script>//Textbox 如下:
<asp:TextBox ID="TextBox5" Width="60px" onkeyup='clearNoNum(this)' runat="server"></asp:TextBox>
难道我out了?