【问题标题】:How to move selected rows from one datagridview to another datagridview in c#?c# - 如何将选定的行从一个datagridview移动到另一个datagridview?
【发布时间】:2018-06-07 05:42:26
【问题描述】:

我尝试使用此代码将选定的行从 datagridview2 移动到 datagridview1。但是当我单击添加按钮以从 datagridview2 移动选定的行时。它还添加到datagridview 2。但是通过异常发生错误“对象引用未设置为对象的实例”。如何解决这个问题。我的代码如下

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

我需要这样做。但是应该通过单击加载按钮加载数据

【问题讨论】:

  • 您是否可以提供有关异常的更多详细信息?它抛出了哪条线?等等
  • @AntiqTech 一次运行 foreachloop 并在“bool checkedCell = (bool)dataGridView2.Rows[n].Cells[0].Value;”中抛出异常
  • bool checkedCell = (bool)dataGridView2.Rows[n].Cells[0].Value; 不应该是bool checkedCell = (bool)row.Cells[0].Value;吗?另外:您显示的代码不是移动而是复制。

标签: c# datagridview


【解决方案1】:

在 datagridview2 中添加行时,必须将布尔列的值设置为:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多