在DataGridView控件中验证数据输入

Posted on 2019-01-01 12:04  努力成长静待花开  阅读(853)  评论(0编辑  收藏  举报

实现效果:

  

知识运用:

  DataGridView控件的公共事件CellValidating

   //将System.Windows.Forms.DataGridViewCellValidatingEventArgs类的Cancel属性设为true  将阻止光标离开单元格

  和CellEndEdit来处理

实现代码:

        private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (e.ColumnIndex == 0)                                                //验证指定列
            {
                float result=0;                                                      //定义值类型并赋值
                if (!(float.TryParse(e.FormattedValue.ToString(), out result)))     //判断是否为数值类型
                {
                    dataGridView1.Rows[e.RowIndex].ErrorText = "请输入数值类型的数据";  //提示错误信息
                    e.Cancel = true;                                                    //事件取消的值
                }
            }
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                dataGridView1.Rows[e.RowIndex].ErrorText = "";
            }
        }