首页 文章

如何在c#中将选定的行从一个datagridview移动到另一个datagridview?

提问于
浏览
0

我尝试使用此代码将所选行从datagridview2移动到datagridview1.But当我单击添加按钮以从datagridview2移动所选行时 . 它还添加到datagridview 2.但是通过异常“ Object reference not set to an instance of an object ”发生错误 . 如何解决这个问题 . 我的代码如下

private void button1_Click(object sender, EventArgs e)
    {

        try
        {
            this.dataGridView1.Rows.Clear();
            foreach (DataGridViewRow row in dataGridView2.Rows)
            {
                int n = dataGridView1.Rows.Add();
                bool checkedCell = (bool)dataGridView2.Rows[n].Cells[0].Value;
                if (checkedCell == true)
                {
                    dataGridView1.Rows[n].Cells[0].Value = row.Cells[1].Value;
                    dataGridView1.Rows[n].Cells[1].Value = row.Cells[2].Value;
                    dataGridView1.Rows[n].Cells[3].Value = row.Cells[3].Value;
                }

            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(" Error " + ex.Message);
        }
    }

我需要这样做 . 但是应该通过点击加载按钮加载数据
enter image description here

1 回答

  • 0

    在datagridview2中添加行时,必须将boolean column的值设置为:

    dataGridView2.Rows.Add("1", "2", "3", false);
    

    其他解决办法:

    this.dataGridView1.Rows.Clear();
            foreach (DataGridViewRow row in dataGridView2.SelectedRows.Cast<DataGridViewRow>().ToList())
            {
                this.dataGridView1.Rows.Add(row.Cells[0].Value, row.Cells[1].Value, row.Cells[2].Value);
            }
    

相关问题