首页 > 解决方案 > 写入符号/字母时出现 DataGridView 错误 System.FormatException

问题描述

我有以下 DataGridview 只需要写入整数,但是如果用户写入任何符号/字母,则会提示此错误。顺便说一句,此列是从数据库加载的,并且值将始终是整数(因此整个列仅用于数字),因此我不知道在用户编辑行时如何验证数字并且不显示此错误。

private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
    {

        if (dataGridView1.Rows[e.RowIndex].Cells[5].Value != null)
        {

            if (dataGridView1.Rows[e.RowIndex].Cells[5].Value == System.DBNull.Value || dataGridView1.Rows[e.RowIndex].Cells[5].Value == null)//Check if cell is not nulll
            {
                dataGridView1.Rows[e.RowIndex].Cells[5].Style.BackColor = Color.White;
            }
            else
            {
                int numero;
                string mimonto = string.Empty + this.dataGridView1.Rows[e.RowIndex].Cells[5].Value;
                bool res = true;
                for (int i = 0; i < mimonto.Length; i++)
                {
                    if (char.IsNumber(mimonto[i]) == true)// if position is a number
                    {

                    }
                    else
                    {
                        res = false;//value is not a number
                    }
                }

                if (res == true)
                {
                    dataGridView1.Rows[e.RowIndex].Cells[5].Style.BackColor = Color.White; //this is a number and color stays as white
                }
                else
                {
                    dataGridView1.Rows[e.RowIndex].Cells[5].Style.BackColor = Color.Red;//color is red if it's not a number 

                    dataGridView1.Rows[e.RowIndex].Cells[5].Value = 0;
                    MessageBox.Show("Debe ingresar valores númericos");




                }

            }
        }
    }

这是符号/字母或任何非数字的错误。

在此处输入图像描述

顺便说一句,是否有任何选项可以仅在单元格上启用数字写入?或者有没有更好的选择来解决这个错误?

标签: c#winforms

解决方案


推荐阅读