这代码能找出datagridview第一列重复的吗

图片说明

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Q698769
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            Dictionary<int, string> dict = dataGridView1.Rows.Cast<DataGridViewRow>()
                .Select((x, i) => new { x = (x.Cells[0].Value ?? "").ToString(), i })
                .ToDictionary(x => x.i + 1, x => x.x);
            if (dict.Any(x => x.Key != e.RowIndex + 1 && x.Value == dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString()))
            {
                MessageBox.Show("和" + dict.First(x => x.Key != e.RowIndex + 1 && x.Value == dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString()).Key.ToString() + "行重复");
            }
        }
    }
}

应该是可以的,难道不行么?

必须可以啊,你如果报错的话,可能是因为你dataGridView1允许用户添加行导致加载完数据后后面有一个空行,这样循环到最后1行时,
判断里面用到的dataGridView1.Rows[i].Cells[0].Value.ToString()会报错,因为这个cells【0】此时是null

图片说明