zoukankan      html  css  js  c++  java
  • 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;
                }
            }

        }

  • 相关阅读:
    四种访问修饰符详解(推荐)
    三层架构中DAL层Sqlhelper怎样快速掌握?(常用)
    ASP.NET中最常用的验证控件使用方法(推荐)
    .NetFrom验证方便的webconfig 配置及前台使用(推荐)
    CefSharp访问需要认证网页或接口(在Request的Headers中添加认证Token)
    CentOS7中配置vsftpd
    CentOS7下安装RabbitMQ
    CentOS7下让Asp.Net Core的网站自动运行
    Winform下的Combox根据值来选中项
    golang简单实现jwt验证(beego、xorm、jwt)
  • 原文地址:https://www.cnblogs.com/richzhang/p/3117898.html
Copyright © 2011-2022 走看看