c# winform datagridview 限制某列只能输入数字

public DataGridViewTextBoxEditingControl CellEdit = null;

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (this.dataGridView1.CurrentCellAddress.X == 9)//获取当前处于活动状态的单元格索引
    {
        CellEdit = (DataGridViewTextBoxEditingControl)e.Control;
        CellEdit.SelectAll();
        CellEdit.KeyPress += Cells_KeyPress; //绑定事件
    }
}

private void Cells_KeyPress(object sender, KeyPressEventArgs e) //自定义事件
{
    if (this.dataGridView1.CurrentCellAddress.X == 9) //获取当前处于活动状态的单元格索引
    {
        if (!(e.KeyChar >= '0' && e.KeyChar <= '9')) e.Handled = true;
        if (e.KeyChar == '\b') e.Handled = false;
    }
}

posted @ 2017-09-08 08:44    阅读(955)  评论(0)    收藏  举报