private DataGridViewTextBoxEditingControl CellEdit = null; // 声明 一个 CellEdit
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)//dataGridView自带事件
{
CellEdit = (DataGridViewTextBoxEditingControl)e.Control; // 赋值
CellEdit.SelectAll();
CellEdit.KeyPress += Cells_KeyPress; // 绑定到事件
}
private void Cells_KeyPress(object sender, KeyPressEventArgs e)//自定义事件
{
if ((e.KeyChar < '0' && e.KeyChar != '.' || e.KeyChar > '9' && e.KeyChar != '.' || ((TextBox)(sender)).Text.IndexOf('.') >= 0 && e.KeyChar == '.') && e.KeyChar != (char)13 && e.KeyChar != (char)8)
{
e.Handled = true;
}
}