【问题标题】:exception:Row provided already belongs to a DataGridView control异常:提供的行已经属于一个 DataGridView 控件
【发布时间】:2012-02-14 06:27:27
【问题描述】:

在处理同一数据网格视图控件中的行时出现以下异常 System.InvalidOperationException 未处理 Message="提供的行已经属于 DataGridView 控件。" 以下是将 currentRowCollection 中的选定行复制为 DataGridViewSelectedRowCollection

的复制方法
copy()
     {
            If (DataGridViewWorkGroupDetails.Rows.Count = 1) Then
                Exit Sub
            End If
            Try
                pasteMode = "copy"
                currentRowCollection = DataGridViewWorkGroupDetails.SelectedRows
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "frmworkgroup:copyRowCollectionError")
            End Try
       }

在粘贴方法中

paste()
{
  Dim row As DataGridViewRow
  Dim myRow As DataGridViewRow
        For Each row In currentRowCollection
            myRow = row
            myRow.Cells.Item(1).Value = String.Empty
            DataGridViewWorkGroupDetails.Rows.Insert(DataGridViewWorkGroupDetails.Rows.Count - 1, myRow)
        Next

}

在粘贴方法中粘贴期间,我希望将第 1 列保留为空字符串 .. 当我将行从一个 datagridview 复制到另一个时,它可以工作,但是当我复制到同一个 datagridview 时,它会添加异常。提供的行已经属于 DataGridView 控件

【问题讨论】:

    标签: vb.net datagridview datarowcollection


    【解决方案1】:

    问题是您正在使用对数据行的引用。

    中的行
    For Each row In currentRowCollection
    

    实际上是对数据视图中已经存在的行的引用。

    在调用插入之前,您需要对行中的数据进行深拷贝。

    myRow = DataGridViewWorkGroupDetails.NewRow();
    myRow.ItemArray = row.ItemArray;
    DataGridViewWorkGroupDetails.Rows.Add(myRow);
    

    我没有测试过这段代码,但它应该可以工作

    【讨论】:

    • 它在 vb.net 中不起作用.. 上面一行中用于 myRow = DataGridViewWorkGroupDetails.NewRow(); 的 datagridview 没有 NewRow() 方法;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 2012-03-11
    • 2013-12-21
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多