如何在使用Winform编辑时只允许特定单元格中的数字


private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(polNumDataGridViewTextBoxColumn_KeyPress);
if (dataGridView1.CurrentCell.ColumnIndex == 3) //Desired Column
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(polNumDataGridViewTextBoxColumn_KeyPress);
}
}
}
private void polNumDataGridViewTextBoxColumn_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}

gridview中的控件不是TextBox。它是一个DataGridViewTextBoxEditingControl

我做了这个工作测试(我的控件名称和列索引不同):

private void DataGridView2_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is DataGridViewTextBoxEditingControl tb) {
tb.KeyPress -= Tb_KeyPress;
tb.KeyPress += Tb_KeyPress;
}
}
private void Tb_KeyPress(object sender, KeyPressEventArgs e)
{
if (dataGridView2.CurrentCell.ColumnIndex == 1 &&
!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}

但是使用数据绑定通常是更好的方法,它可以自动解决问题。例如,当单元格绑定到数字属性或日期时间属性时,它的行为相应

相关内容

最新更新