如何将选定的行从一个datagridview传输到另一个? [英] How to transfer selected rows from one datagridview to another?

查看:66
本文介绍了如何将选定的行从一个datagridview传输到另一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将选定的行从一个datagridview传输到另一个。我使用了组合框textchange事件将所选数据加载到datagrid。因此,对于两个 dataGridView 来说,传输代码都需要执行 dataGridView1.AllowUserToAddRows = false; 。但是由于使用了组合框textchange事件,因此我无法禁止添加新行。如何解决呢?我使用以下代码来传输值:

I try to transfer selected rows from one datagridview to another. I used combobox textchange event to load selected data to datagrid. So that transfer code need to do dataGridView1.AllowUserToAddRows = false; for both dataGridViews. But due to use combobox textchange event I can't disable adding new rows. How to solve this? I use following code to transfer values:

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());
                }
            }
        }
    }


推荐答案

首先尝试从网格中删除行,然后再尝试将其添加到新的网格中。

Start with removing the row from the Grid before you try to add it to the new Grid.

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

这篇关于如何将选定的行从一个datagridview传输到另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆