如何验证 DataGridView 中的单元格?

OPV*_*OPV -1 c# datagridview winforms

我有DataGridView几个细胞。如何验证所有单元格并突出显示无效单元格?

填充单元格后应进行验证。

我尝试使用这种方式:

void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
}
Run Code Online (Sandbox Code Playgroud)

但是我需要为每个字段(列)设置一些验证规则。例如,检查数字或字符串。

小智 6

你可以试试这个代码。当我们要编辑 cell('EmployeeName') 时,它避免使用整数值。当焦点丢失在所选单元格中显示错误消息时。

这是我的模型

namespace WindowsFormsApplication1
{
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }
        public string EmployeeAddress { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的代码

 namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            List<Employee> EmployeeList = new List<Employee>();
            public Form1()
            {
                InitializeComponent();
            }

            private void Form1_Load(object sender, EventArgs e)
            {


                Employee emp = new Employee();

                emp.EmployeeAddress = "polonnaruwa";

                emp.EmployeeId = 1;
                emp.EmployeeName = "Kasun";

                EmployeeList.Add(emp);
                Employee emp1 = new Employee();
                emp1.EmployeeAddress = "Kandy";

                emp1.EmployeeId = 2;
                emp1.EmployeeName = "Bimal";

                EmployeeList.Add(emp1);

                Employee emp2 = new Employee();
                emp2.EmployeeAddress = "New Town";

                emp2.EmployeeId = 3;
                emp2.EmployeeName = "ASheain";

                EmployeeList.Add(emp2);

                dataGridView1.DataSource = EmployeeList;

            }

            private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
            {
                if (this.dataGridView1.Columns[e.ColumnIndex].Name == "EmployeeName")
                {
                    int RowIndex = e.RowIndex;
                    int columnIndex = e.ColumnIndex;
                    if (e.Value != null)
                    {

                        string stringValue = (string)e.Value;
                        int val;
                        if (int.TryParse(stringValue, out val))
                        {

                            label1.Text = "it is integer";
                            dataGridView1.Rows[RowIndex].Cells[columnIndex].Value = "Please Enter String Value";

                        }
                        else
                        {
                            label1.Text = "it is not integer";

                        }

                    }
                }

            }

            private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
            {

            }
        }
    } 
Run Code Online (Sandbox Code Playgroud)