[英]Duplicating Rows In DataGridView
以下代碼將制表符分隔的文件加載到我的 DataGridView 中(從數據文件加載 1 條記錄)。 所有這些都完美無缺,但是,我需要將此記錄復制 X 次。 一旦行被復制,我最終需要編輯一些字段並寫入一個添加了行的新文件。
我試過動態添加行,但它對我大喊大叫說我不能,因為數據是綁定的。
建議?
Dim file As String = "Temp.txt"
Dim path As String = "C:\Temp\"
Dim ds As New DataSet
Dim tbl As New DataTable
Try
If IO.File.Exists(IO.Path.Combine(path, file)) Then
Dim ConStr As String = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
path & ";Extended Properties=""Text;HDR=No;FMT=TabDelimited\"""
Dim conn As New OleDb.OleDbConnection(ConStr)
Dim da As New OleDb.OleDbDataAdapter("Select * from " & _
file, conn)
da.Fill(ds, "TextFile")
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
DataGridView1.DataSource = ds.Tables(0)
您不能直接添加到數據綁定的DataGridView
,因為數據駐留在別處,而 DGV 只是顯示那里的內容。 向DataTable
添加行:
Dim dr = ds.Tables(0).NewRow()
這將創建一個新行,其中包含基於表為其定義的列。 將新項目的數據添加到其中,然后將其添加到表中:
dr.Item(0) = "something" ' add to column one
... etc
ds.Tables(0)Rows.Add(dr)
你並沒有真的需要創建一個DataSet
為你所擁有的這么遠。 選擇:
Private myDT As New DataTable
...
da.Fill(myDT)
從字面上克隆一行的數據:
Dim dr As DataRow
For n As Integer = 0 To NumberOfDuplicates
dr = myDT.NewRow ' new DataRow
For c As Integer = 0 To myDT.Columns.Count - 1 ' copy data from 0 to NewRow
dr.Item(c) = myDT.Rows(0).Item(c)
Next
myDT.Rows.Add(dr) ' add NewRow to datatable
Next n
請注意,您需要為每個克隆創建一個新行,內部循環將數據從 row(0) 復制到每個新行。
'Hope This helps DGV1 is the datagridview
'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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.