防止GridView添加冗余行

时间:2015-01-30 06:40:38

标签: c# winforms gridview

我有以下代码:

 foreach (DataGridViewRow row in form1.dataGridView1.SelectedRows)
        {

            int index = dataGridView2.Rows.Add(row.Clone() as DataGridViewRow);
            foreach (DataGridViewCell cell in row.Cells)
            {
                dataGridView2.Rows[index].Cells[cell.ColumnIndex].Value = cell.Value;
            }

因此,我将在GridView中选择的行复制到另一个Gridview。现在,我希望他检查是否已将行添加到第二行并打开消息框。怎么做?我还没有找到适合我的解决方案。

1 个答案:

答案 0 :(得分:1)

  foreach (DataGridViewRow row in form1.dataGridView1.SelectedRows)
        {
            bool isnotexist = true;
            foreach (DataGridViewRow rowgrid2 in dataGridView2.Rows)
            {
                if (rowgrid2.Cells[0].Value.ToString() == row.Cells[0].Value.ToString())
                {
                    isnotexist = false;
                    break;
                }
            }
            if (isnotexist)
            {
                int index = dataGridView2.Rows.Add(row.Clone() as DataGridViewRow);
                foreach (DataGridViewCell cell in row.Cells)
                {
                    dataGridView2.Rows[index].Cells[cell.ColumnIndex].Value = cell.Value;
                }
            }
        }

希望这段代码有帮助......