1、禁止所有被编辑
设置DataGridView的属性ReadOnly为true即可
2、禁止某列被编辑
dataGridView1.Columns[i].ReadOnly = true;
3、限制某些列只能输入数字
设置事件:
//限制某些列编辑时只能输入数字
public DataGridViewTextBoxEditingControl CellEdit = null;
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if ((this.dataGridView1.CurrentCellAddress.X == 2) || (this.dataGridView1.CurrentCellAddress.X == 4))//获取当前处于活动状态的单元格索引
{
CellEdit = (DataGridViewTextBoxEditingControl)e.Control;
CellEdit.SelectAll();
CellEdit.KeyPress += Cells_KeyPress; //绑定事件
}
}
private void Cells_KeyPress(object sender, KeyPressEventArgs e) //自定义事件
{
if ((this.dataGridView1.CurrentCellAddress.X == 2) || (this.dataGridView1.CurrentCellAddress.X == 4))//获取当前处于活动状态的单元格索引
{
if (!(e.KeyChar >= '0' && e.KeyChar <= '9')) e.Handled = true;
if (e.KeyChar == '\b') e.Handled = false;
}
}