实现效果:

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

 

相关文章:

  • 2021-08-03
  • 2022-12-23
  • 2021-12-29
  • 2022-12-23
  • 2022-12-23
  • 2021-05-05
  • 2021-09-05
猜你喜欢
  • 2022-12-23
  • 2021-12-19
  • 2022-12-23
  • 2022-01-03
  • 2022-03-01
  • 2021-05-18
  • 2021-10-22
相关资源
相似解决方案