2011-10-13 132 views
0

使用VB.Net如何在gridview中将一行复制到另一行

我想将一行数据复制到另一行。

我使用在GridView复选框,如果我点击则复选框,按下按钮选定行复制到新的单元格(行)

下面代码工作进行删除,而不是工作拷贝行

代码

Private Sub btncopy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncopy.Click 
     For Each m_row As System.Windows.Forms.DataGridViewRow In Me.grvList.Rows 
      If m_row.Cells("chksel").Value = True Then 
       Me.grvList.Rows.Add(m_row) 
      ' Me.grvList.Rows.Remove(m_row) 
      End If 
     Next 
    End Sub 

上面的代码被表示“已经提供行属于一个DataGridView控制”。误差作为

我的代码有什么问题。

需要VB.Net代码帮助

回答

2

您不能再次添加完全相同的行。您将需要创建一个新的行,从该行正在复制而不是值填充它,然后将新行添加到grvList.Rows

我不知道你在每个单元什么样的价值观,但只要他们是值类型,类似于下面的东西应该工作:

For Each m_row As System.Windows.Forms.DataGridViewRow In Me.grvList.Rows 
     If m_row.Cells("chksel").Value = True Then 
      'Create new row to hold duplicated values 
      Dim NewRow As DataRow = grvList.NewRow() 
      'loop thru existing rows to copy values 
      For i As Integer = 0 To m_row.Cells.Count - 1 
       NewRow(i) = m_row.Cells(i).Value 
      Next 
      'Add newly create row to table 
      Me.grvList.Rows.Add(NewRow) 
      ' Me.grvList.Rows.Remove(m_row) 
     End If 
    Next 

请记住,如果在任一单元格的项目,你仍然会引用相同的项目,而不是创建引用类型该项目的副本。就像您在简单地调用您所在的同一行上的添加一样。

对不起,我错过了一排排的DataGridView行,而不是被绑定的DataTable ...这应该做的伎俩在这种情况下:

  For Each m_row As System.Windows.Forms.DataGridViewRow In Me.grvList.Rows 
       If m_row.Cells("chksel").Value = True Then 
        'Create new row to hold duplicated values 
        Dim NewRow As DataGridViewRow = m_row.Clone 
        'Add newly create row to table 
        Me.grvLIst.Rows.Add(NewRow) 
       End If 
      Next 
+0

可否请你发布一些示例代码。 – Gopal

+0

以上编辑包含一个示例。 – Jay

+0

谢谢,它显示错误在这行“Dim NewRow As DataRow = grvList.NewRow()”。 – Gopal

1
'To copy Row 
Private Sub CopyButton_Click(sender As System.Object, e As System.EventArgs) Handles CopyButton.Click 
    CopyRowIndex = DGV1.CurrentRow.Index 
End Sub 

'To Paste Row 
Private Sub PasteButton_Click(sender As System.Object, e As System.EventArgs) Handles PasteButton.Click 
    PasteRowIndex = DGV1.CurrentRow.Index 
    For index As Int32 = 0 To DGV1.ColumnCount - 1 
     DGV1.Rows(CInt(PasteRowIndex)).Cells(index).Value = DGV1.Rows(CInt(CopyRowIndex)).Cells(index).Value 
    Next 

End Sub 

'To Duplicate Rows 
Private Sub DuplicateButton_Click(sender As System.Object, e As System.EventArgs) Handles DuplicateButton.Click 
    CopyRowIndex = DGV1.CurrentRow.Index 
    DGV1.Rows.Add() 
    DuplicateRowIndex = DGV1.Rows.Count - 1 
    For index As Int32 = 0 To DGV1.ColumnCount - 1 
     DGV1.Rows(CInt(DuplicateRowIndex)).Cells(index).Value = DGV1.Rows(CInt(CopyRowIndex)).Cells(index).Value 
    Next 
End Sub 
相关问题