#region DGV指定列只允许输入数字和小数点(一个小数点) 类似金额
public DataGridViewTextBoxEditingControl CellEdit { get; set; }//声明一个CellEdit
public void gridEnter_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
CellEdit = (DataGridViewTextBoxEditingControl)e.Control;//赋值
CellEdit.SelectAll();
CellEdit.KeyPress += Cells_KeyPress;
}
// 自定义事件
public void Cells_KeyPress(object sender, KeyPressEventArgs e)
{
//if (_frm.grizdEnter.CurrentCellAddress.X == 2 || _frm.gridEnter.CurrentCellAddress.X == 4) // 判断当前列是不是要控制的列
//{
if (!(Char.IsNumber(e.KeyChar) || e.KeyChar == 46 || e.KeyChar == (Char)Keys.Back))
{
e.Handled = true;
return;
}
System.Windows.Forms.TextBox tb = (System.Windows.Forms.TextBox)sender;//System.Windows.Forms.TextBox
string strMathchValue = tb.Text;
Regex rx = new Regex(@"^[0-9]*(.)?[0-9]*$", RegexOptions.IgnoreCase);
//判断是否为退格键
if (e.KeyChar == (Char)Keys.Back)
{
///判断输入控件选择文本的长度
if (tb.SelectionLength == 0)
{//未选文本中时处理
if (tb.SelectionStart > 0)
{//选择的开始位置大于0时处理
//strMathchValue.Remove(tb.SelectionStart, 1);
strMathchValue.Remove(tb.SelectionStart-1, 1);
}
}
else
{//有选中文本时处理
strMathchValue.Remove(tb.SelectionStart, tb.SelectionLength);
}
}
else
{
//将当前输入的字符号插入到原来的字符串中
strMathchValue = strMathchValue.Insert(((System.Windows.Forms.TextBox)sender).SelectionStart, e.KeyChar.ToString());
}
if (rx.IsMatch(strMathchValue) == false)
{
e.Handled = true;
}
//}
}
#endregion
#region DGV键盘屏蔽事件 只允许输入数字
public DataGridViewTextBoxEditingControl CellEdit = null; // 声明一个CellEdit
public void xDataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is DataGridViewTextBoxEditingControl)
{
CellEdit = (DataGridViewTextBoxEditingControl)e.Control; //赋值
CellEdit.SelectAll();
CellEdit.KeyPress += Cells_KeyPress; //绑定到事件
}
}
//自定义事件
public void Cells_KeyPress(object sender, KeyPressEventArgs e)
{
//if (_frm.xDataGridView1.CurrentCellAddress.X == 3) // 判断当前列是不是要控制的列)
//{
if ((Convert.ToInt32(e.KeyChar) < 48 || Convert.ToInt32(e.KeyChar) > 57) && Convert.ToInt32(e.KeyChar) != 46 && Convert.ToInt32(e.KeyChar) != 8 && Convert.ToInt32(e.KeyChar) != 13)
{
e.Handled = true; // 输入非法就屏蔽
}
else
{
if (Convert.ToInt32(e.KeyChar) == 46)
{
e.Handled = true;
}
}
//}
}
#endregion
DGV 指定列 只允许输入“数字和小数点(金额)” 和“数字”
最新推荐文章于 2021-12-15 10:55:42 发布