我尝试将所选行从一个数据网格视图传输到另一个数据网格视图。我使用combobox textchange事件将所选数据加载到datagrid。因此,转移代码需要为dataGridView1.AllowUserToAddRows = false;
执行dataGridView
。但由于使用了combobox textchange事件,我无法禁用添加新行。怎么解决这个?我使用以下代码来传输值:
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());
}
}
}
}
答案 0 :(得分:0)
在尝试将其添加到新网格之前,先从网格中删除该行。
foreach (GridViewRow row in fromGridView.SelectedRows.OfType<DataGridViewRow>().ToArray())
{
fromGridView.Rows.Remove(row);
toGridView.Rows.Add(row);
}