在datagridview的EditingControlShowing事件里面添加代码:
if (this.dgv_pch.Columns[dgv_pch.CurrentCell.ColumnIndex].HeaderText == "批内序号")//判断是哪列的单元格需要限制
{
(dgv_pch.Columns[dgv_pch.CurrentCell.ColumnIndex] as DataGridViewTextBoxColumn).MaxInputLength = 4;//限制只能输入内容长度为4
e.Control.KeyPress += new KeyPressEventHandler(EditingControl_KeyPress);//限制只能输入数字
//e.Control.KeyPress -= new KeyPressEventHandler(EditingControl_KeyPress);
}
private void EditingControl_KeyPress(object sender, KeyPressEventArgs e)
{
if (Convert.ToInt32(e.KeyChar) == 8)
{
e.Handled = false;
}
else
{
Regex numRegex = new Regex(@"^(-?[0-9])$"); // 匹配正则表达式
Match result = numRegex.Match(Convert.ToString(e.KeyChar));
if (result.Success) // 输入的不是数字
{
e.Handled = false; // textBox内容不变
}
else
{
e.Handled = true; // 将现在textBox的值保存下来
}
}
}