DataGridView禁止所有被编辑/某列被编辑/限制只能输入数字

本文介绍了如何在DataGridView中实现禁止所有列被编辑、特定列只读以及限制某些列只能输入数字的方法,包括设置ReadOnly属性和使用事件处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值