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

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

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) 
您可以使用`EditingControlShowing`事件和`DefaultCellStyle`属性来限制`DataGridView`中的单元格只能输入数字。以下是实现此功能的示例代码: ```csharp private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { // 判断当前单元格是否为数字单元格 if (dataGridView1.CurrentCell.ColumnIndex == 0 || dataGridView1.CurrentCell.ColumnIndex == 1) { TextBox textBox = e.Control as TextBox; if (textBox != null) { // 只允许输入数字和控制键 textBox.KeyPress += new KeyPressEventHandler(textBox_KeyPress); } } } private void textBox_KeyPress(object sender, KeyPressEventArgs e) { // 判断按键是否为数字或控制键 if (!char.IsDigit(e.KeyChar) && e.KeyChar != '\b' && e.KeyChar != '.') { e.Handled = true; } // 判断小数点是否已经存在 if (e.KeyChar == '.' && ((TextBox)sender).Text.IndexOf('.') > -1) { e.Handled = true; } } // 设置单元格为数字单元格 private void Form1_Load(object sender, EventArgs e) { dataGridView1.Columns[0].DefaultCellStyle = new DataGridViewCellStyle { NullValue = 0, Format = "N2" }; dataGridView1.Columns[1].DefaultCellStyle = new DataGridViewCellStyle { NullValue = 0, Format = "N2" }; } ``` 在上面的代码中,`EditingControlShowing`事件用于获取当前单元格的编辑控件,并将其转换为`TextBox`类型。然后,我们将`KeyPress`事件添加到`TextBox`控件中,以便只允许输入数字和控制键。最后,我们使用`DefaultCellStyle`属性将单元格设置为数字单元格,并指定格式为`N2`,以便在单元格中显示小数点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值