如何在c#中将选定行从一个datagridview移动到另一个datagridview?
我尝试用这段代码将选定的行从datagridview2移动到datagridview1。但当我单击添加按钮从datagridview2移动选定的行时。并且它还添加到datagridview 2中。但是由于异常“对象引用未设置为对象的实例”而发生错误。如何解决此问题。我的代码如下如何在c#中将选定行从一个datagridview移动到另一个datagridview?,c#,datagridview,C#,Datagridview,我尝试用这段代码将选定的行从datagridview2移动到datagridview1。但当我单击添加按钮从datagridview2移动选定的行时。并且它还添加到datagridview 2中。但是由于异常“对象引用未设置为对象的实例”而发生错误。如何解决此问题。我的代码如下 private void button1_Click(object sender, EventArgs e) { try { this.dataGrid
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);
}
}
我需要这样做。但是数据应该通过点击加载按钮加载
在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);
}
this.dataGridView1.Rows.Clear();
foreach(dataGridView2.SelectedRows.Cast().ToList()中的DataGridViewRow行)
{
this.dataGridView1.Rows.Add(row.Cells[0].Value,row.Cells[1].Value,row.Cells[2].Value);
}
的可能副本的可能副本您是否可以提供有关例外情况的更多详细信息?投哪一行?etc.@AntiqTech运行foreachloop onece并在“bool checkedCell=(bool)dataGridView2.Rows[n].Cells[0].Value;“bool checkedCell=(bool)dataGridView2.Rows[n].Cells[0].Value;不应该是bool checkedCell=(bool)行。单元格[0]。值代码>?另外:显示的代码不是移动的,而是复制的。