2011-10-13 133 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 
相關問題