c# - c# - 如何将选定的行从一个datagridview移动到另一个datagridview?
问题描述
我尝试使用此代码将选定的行从 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);
}
}
解决方案
在 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);
}
推荐阅读
- pandas - 使用任何方法
- php - 如何在基于 Symfony 2/3 的项目中重构路径名称,如 `AppBundle:SomeFolder:someFile` 以在 Symfony 4+ 中使用?
- python - matplotlib:如何为 log-scale 主轴添加线性 secondary_yaxis?
- python-3.x - 我没有收到电子邮件验证以激活创建的用户
- javascript - Google Apps 脚本 - 在另一个网页上自动填充文本框
- amazon-web-services - 如何将 AWS 管道指定为 CDK 中代码构建项目的源提供者?
- python - 在另一个程序(Unity3D)关闭后启动 python 脚本
- spring - Spring RestTemplate ResourceAccessException:POST 请求上的 I/O 错误无法响应
- c# - System.NotSupportedException: '不支持指定的路径格式。'
- java - Log4j.properties 不会为 LOGGER.info()、LOGGER.error() 语句生成带有时间戳的日志