2014-01-16 61 views
0

我正在使用datagridview将多个.txt文件保存到文件夹。列1是文件名,列2是文件的内容。Datagridview到多个.txt文件

我想循环整个datagridview,但生成的唯一.txt文件是小箭头在行标题中的那个。即使我突出显示/选择了多行,也会发生这种情况。如何为所有选定的行生成.txt文件?谢谢。

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click 
    For Each row As DataGridViewRow In DataGridView1.SelectedRows 
     My.Computer.FileSystem.WriteAllText("D:\samplefolder\" & DataGridView1.SelectedCells(0).Value.ToString & ".txt", DataGridView1.SelectedCells(1).Value.ToString, False) 
    Next 
End Sub 

回答

0

For Each循环的全部要点是按顺序访问列表中的每个项目。该代码中的循环控制变量是'row',但您从不在循环中使用该变量。你总是在循环中使用相同的两个单元格,所以你只需一遍又一遍地写同一个文件。在循环内部,'row'包含当前行,所以使用它。从'行'获取你想要的两个单元格。

顺便说一下,最好使用Path.Combine合并部分路径。

+0

感谢您的答复,但你解释一些示例代码将是有益的。 – user3080392

+1

所以你会有点努力。您在我的7分钟后发布了您的评论。你在7分钟内做了什么努力来遵循我的指示?说明很简单。跟着他们。如果你尝试失败,那么我可以帮忙,但如果你甚至不尝试,那为什么我呢? – jmcilhinney

0

下面的代码为我工作:

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click 
For Each row As DataGridViewRow In DataGridView1.SelectedRows 
    My.Computer.FileSystem.WriteAllText("D:\samplefolder\" & row.Cells(0).Value.ToString & ".txt", row.Cells(1).Value.ToString, False) 
Next row 

末次