简体   繁体   English

将datagridview行移动到另一个datagridView

[英]move datagridview Row to another datagridView

I've gone through the other answers for this kind of question, nothing has really worked well so far. 对于此类问题,我已经浏览了其他答案,到目前为止,还没有任何方法能很好地工作。

I have a foreach loop that should add the the row from the source datagridview to the destination datagridview then remove that row from the source. 我有一个foreach循环,应该将行从源datagridview到目标datagridview然后从源中删除该行。

The invalid operation exception is: Row provided already belongs to a DataGridView control. 无效的操作异常是: Row provided already belongs to a DataGridView control.

I couldn't get ...Rows.Copy() to work either. 我也无法使...Rows.Copy()工作。 Any ideas? 有任何想法吗?

foreach (DataGridViewRow selRow in fromDataGridView.SelectedRows)
{
    toDataGridView.Rows.Add(selRow);
    fromDataGridView.Rows.Remove(selRow);
}

You need to remove the row from fromDataGridView before you add it to toDataGridView . 您需要先从fromDataGridView删除该行, fromDataGridView再将其添加到toDataGridView

But you're modifying the collection inside the foreach loop - that won't work. 但是您要在foreach循环中修改集合-这将无法工作。

The workaround is to copy the collection for use in the foreach . 解决方法是复制集合以供foreach使用。

Try this: 尝试这个:

foreach (DataGridViewRow selRow in fromDataGridView.SelectedRows.OfType<DataGridViewRow>().ToArray())
{
    fromDataGridView.Rows.Remove(selRow);
    toDataGridView.Rows.Add(selRow);
}

Here is an example of what you could do or try.. 这是您可以做或尝试的示例。

its happening when one row is removed the rows count decrements too so if you put your code in for loop and run it in reverse it would work fine have a look: 删除一行时发生这种情况,行数也会减少,因此,如果将代码放入for循环并以相反的方式运行它,则可以正常运行:

for (int selRow = dataGridView1.Rows.Count -1; selRow >= 0 ; selRow--)
{
   toDataGridView.Rows.Add(selRow);
   fromDataGridView.Rows.Remove(selRow);     
}

Adding a new row directly to DataGridView is not possible when there is BindingSource . 如果存在BindingSource则不可能直接向DataGridView添加新行。

You should add row to the BindingSource of second view and let it to add the row to its grid. 您应该将行添加到第二个视图的BindingSource ,并让其将行添加到其网格中。

I've tested the below code in a working solution. 我已经在一个可行的解决方案中测试了以下代码。

var selectedRows = dataGridView1.SelectedRows;
int count = dataGridView1.SelectedRows.Count;
for (int i = 0; i < count; i++)
{
    bindingSource2.Add(bindingSource1[selectedRows[i].Index]);
    dataGridView1.Rows.Remove(selectedRows[i]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM