如何限制用户在DataGridView列中的特定单元格中只输入数值? [英] How can I restrict a user to entering only numeric values in a specific cell in a DataGridView column?
本文介绍了如何限制用户在DataGridView列中的特定单元格中只输入数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 DataGridView
控件,其中我想限制用户只输入特定列下的单元格的数值。如何在 DataGridView
单元格中完成这种类型的验证?
I have a DataGridView
control in which I want to restrict the user to entering only numeric values for a cell under a particular column. How can I accomplish this type of validation in DataGridView
cells?
我可以创建一个简单的文本框,但是如何验证一个 DataGridView
Cell?
It is possible when I create a simple text box, but how can I validate a DataGridView
Cell?
推荐答案
- 添加EditingControlShowing的事件
- 在EditingControlShowing中,检查当前单元格是否在所需的列中。
- 注册新的在EditingControlShowing中的KeyPress事件(如果上述条件为真)
- 删除以前在EditingControlShowing中添加的任何KeyPress事件。
- 在KeyPress事件中,检查如果密钥不是数字,则取消输入。
- Add an event of EditingControlShowing
- In EditingControlShowing, check that if the current cell lies in the desired column.
- Register a new event of KeyPress in EditingControlShowing(if above condition is true).
- Remove any KeyPress event added previously in EditingControlShowing.
- In KeyPress event, check that if key is not digit then cancel the input.
示例:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
if (dataGridView1.CurrentCell.ColumnIndex == 0) //Desired Column
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
}
}
}
private void Column1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
这篇关于如何限制用户在DataGridView列中的特定单元格中只输入数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文