首页 > 解决方案 > 如何将选定的行从一个 datagridview 传输到另一个?

问题描述

我尝试将选定的行从一个 datagridview 传输到另一个。我使用组合框文本更改事件将选定的数据加载到数据网格。因此,传输代码需要dataGridView1.AllowUserToAddRows = false;为两个dataGridViews 做。但由于使用组合框 textchange 事件,我无法禁用添加新行。如何解决这个问题?我使用以下代码来传输值:

private void btnaddtoanother_Click(object sender, EventArgs e)
    {
        for (int i = 0; i <= dataGridView2.Rows.Count - 1; i++)
        {
            bool rowAlreadyExist = false;
            bool checkedCell = (bool)dataGridView2.Rows[i].Cells[0].Value;
            if (checkedCell == true)
            {
                DataGridViewRow row = dataGridView2.Rows[i];
                if (dataGridView1.Rows.Count != 0)
                {
                    for (int j = 0; j <= dataGridView1.Rows.Count - 1; j++)
                    {
                        if (row.Cells[0].Value.ToString() == dataGridView1.Rows[j].Cells[0].Value.ToString())
                        {
                            rowAlreadyExist = true;
                            break;
                        }
                    }
                    if (rowAlreadyExist == false)
                    {
                        dataGridView2.Rows.Add(row.Cells[0].Value.ToString());
                        dataGridView2.Rows.Add(row.Cells[1].Value.ToString());
                        dataGridView2.Rows.Add(row.Cells[3].Value.ToString());
                    }
                }
                else
                {
                    dataGridView2.Rows.Add(row.Cells[0].Value.ToString());
                    dataGridView2.Rows.Add(row.Cells[1].Value.ToString());
                    dataGridView2.Rows.Add(row.Cells[3].Value.ToString());
                }
            }
        }
    }

标签: c#datagridview

解决方案


在尝试将其添加到新网格之前,先从网格中删除该行。

foreach (GridViewRow row in fromGridView.SelectedRows.OfType<DataGridViewRow>().ToArray())
{
    fromGridView.Rows.Remove(row);
    toGridView.Rows.Add(row);
}

推荐阅读