• DataGridView 输入数据验证格式(实例)


    在DataGridView属性里面添加dgvOne_CellValidating事件,然后根据需要以后。

       private void dgvOne_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            //可编辑的列2、3、4、5、6(实际显示的列减1)列需要输入0~9的自然数.
            if ( e.ColumnIndex == 2 || e.ColumnIndex == 3 || e.ColumnIndex == 4 || e.ColumnIndex == 5 || e.ColumnIndex == 6)
            {
                int outDb = 0;
                if (int.TryParse(e.FormattedValue.ToString(), out outDb))
                {
                    e.Cancel = false;
                }
                else
                {
                    e.Cancel = true;//数据格式不正确则还原
                    MessageBox.Show("请输入0~9的自然数!", "提交提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    dgvOne.CancelEdit();
                }
            }

          //第二列验证时间格式
            if (e.ColumnIndex == 1)
            {
                DateTime  outDb =DateTime.Now;
                if (DateTime.TryParse(e.FormattedValue.ToString(), out outDb))
                {
                    e.Cancel = false;
                }
                else
                {
                    e.Cancel = true;//数据格式不正确则还原
                    MessageBox.Show("输入日期格式不正确,请重新输入!", "提交提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    dgvOne.CancelEdit();
                }
            }

                //第一列验证正整数

            if (e.ColumnIndex == 0)
            {
                Regex notWholePattern = new Regex(@"^[0-9]\d*$");
                if (notWholePattern.IsMatch(e.FormattedValue.ToString(), 0))
                {
                    e.Cancel = false;
                }
                else
                {
                    e.Cancel = true;//数据格式不正确则还原
                    MessageBox.Show("输入序号的格式不正确,请重新输入正整数!", "提交提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    dgvTwo.CancelEdit();
                }
            }

           //长度验证

            if (e.ColumnIndex == 6 || e.ColumnIndex == 7)
            {
                string str = e.FormattedValue.ToString();
                int leng = str.Length;
                if (leng > 1)
                {
                    e.Cancel = true;//数据格式不正确则还原
                    MessageBox.Show("只能输入一位0~9的自然数,请重新输入!", "提交提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    dgvTwo.CancelEdit();

                }
                else
                {
                    e.Cancel = false;
                }
            }

        }

  • 相关阅读:
    FFMPEG音视频基础问题和被面试问到的东西
    OpenGL学习
    FFMPEG起航之旅
    SurfaceView、TextureView对比和学习
    对文件拷贝、删除操作、对时间的计算以及转化
    音视频开发
    企业级Android应用架构设计与开发
    屏幕分辨率的适配&&开发文档的介绍
    设计模式的学习
    自定义Dialog的模版
  • 原文地址:https://www.cnblogs.com/richzhang/p/3117898.html
Copyright © 2020-2023  润新知