dataGridView中只能输入数字

来源:互联网 发布:安排课程表软件 编辑:程序博客网 时间:2024/05/16 02:15

  private DataGridViewTextBoxEditingControl CellEdit = null; // 声明 一个 CellEdit


        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)//dataGridView自带事件
        {
            CellEdit = (DataGridViewTextBoxEditingControl)e.Control; // 赋值          
            CellEdit.SelectAll();
            CellEdit.KeyPress += Cells_KeyPress; // 绑定到事件

        }

 


        private void Cells_KeyPress(object sender, KeyPressEventArgs e)//自定义事件
        {
            if ((e.KeyChar < '0' && e.KeyChar != '.' || e.KeyChar > '9' && e.KeyChar != '.' || ((TextBox)(sender)).Text.IndexOf('.') >= 0 && e.KeyChar == '.') && e.KeyChar != (char)13 && e.KeyChar != (char)8)
            {
                e.Handled = true;
            }
        }

原创粉丝点击