2015-06-24 58 views
2

以下代码将制表符分隔的文件加载到我的DataGridView中(从数据文件加载1条记录)。所有这些都很完美,但是,我需要重复记录X次的时间。一旦行被复制,我需要最终编辑一些字段并写入添加了行的新文件。在DataGridView中复制行

我尝试过动态添加行,但它对我大声说我不能,因为数据是绑定的。

对此提出建议?

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) 
+0

将行添加到'ds.Tables(0)' – Plutonix

+0

我不知道在加载数据之前需要添加多少行。 – Muhnamana

+0

您可以随时将数据行添加到DataTable中,您无法直接将它们添加到DGV(是吗 - 文件只有一行?) – Plutonix

回答

1

您不能直接添加到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 

注意,从行内循环复制数据( 0)到每个新的。

+0

该文件有很多字段,100+和id必须定义每个字段。没有办法复制整行? – Muhnamana

+0

...我没有完成那部分 - 请参阅更新 – Plutonix

+0

我认为我在我的头上,仍然在学习绳索和混淆克隆的代码需要放在关系到表时传递到datagridview。我需要退后一步... – Muhnamana

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