在DataGridView控件中验证数据输入

Posted feiyucha

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在DataGridView控件中验证数据输入相关的知识,希望对你有一定的参考价值。

实现效果:

  技术分享图片

知识运用:

  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 = "";
            }
        }

 

以上是关于在DataGridView控件中验证数据输入的主要内容,如果未能解决你的问题,请参考以下文章