我的 VB.NET 应用程序有一个 datagridview (Named = "DGV"),它有 4 列。我想用数据网格行编写多个文本文件。文本文件的名称应该是第 1 列单元格的值,文本文件的文本应该是第 3 列单元格的值。附加的图像将清除所有内容。请帮助。
问问题
1427 次
2 回答
1
这是一种方法。首先,我DataTable
从 DataGridView 创建一个以简化任务。然后我Linq-To-DataTable
用来获取我需要的东西(dir
是你目录的路径)。
Dim table = New DataTable()
For i As Int32 = 0 To dgv.Columns.Count - 1
table.Columns.Add(dgv.Columns(i).Name)
Next
For Each gvRow As DataGridViewRow In dgv.Rows
Dim row = table.Rows.Add()
For col As Int32 = 0 To dgv.Columns.Count - 1
row(col) = gvRow.Cells(col).Value
Next
Next
Dim fileInfos = From r In table
Select New With {
.File = New FileInfo(Path.Combine(dir, r.Field(Of String)(0))),
.Content = r.Field(Of String)(2)
}
现在创建文本文件并写入文本:
For Each fileInfo In fileInfos
Try
fileInfo.File.Create()
Using writer = fileInfo.File.CreateText()
writer.Write(fileInfo.Content)
End Using
Catch ex As Exception
' log etc.
End Try
Next
我正在使用 .NET 2.0 版,但无法更改
这是 .NET 2 版本:
For Each row As DataRow In table.Rows
If Not row.IsNull(0) AndAlso row(0).ToString().Length <> 0 Then
Dim path = IO.Path.Combine(dir, row(0).ToString())
Dim file = New IO.FileInfo(path)
Try
file.Create()
Using writer = file.CreateText()
Dim content = ""
If Not row.IsNull(2) Then content = row(2).ToString()
writer.Write(content)
End Using
Catch ex As Exception
' log etc.
End Try
End If
Next
于 2012-10-11T15:19:22.990 回答
0
我设计了这段代码,我想知道它工作得很好。首先在“Public Class Form1”之后的代码顶部创建一个布尔属性
Public Property SelectedIdexLock As Boolean = False
现在在 Datagride1 选择更改:
If SelectedIdexLock = True Then
My.Computer.FileSystem.WriteAllText("C:\Users\YOUR USER NAME HERE\Desktop\" & Datagride1.SelectedCells(0).Value.ToString & ".txt", Datagride1.SelectedCells(2).Value.ToString, False)
End If
好的,这是最后一步,在测试按钮 (Button1) 单击:
Dim RowsCount As Integer = Datagride1.Rows.Count.ToString
Datagride1.Rows(0).Selected = True
Datagride1.Rows(0).Selected = False
For Each row In Datagride1DataSet.Table1.Rows
Dim i As Integer
For i = 0 To RowsCount
If i = RowsCount Then
SelectedIdexLock = False
Exit Sub
Else
SelectedIdexLock = True
Datagride1.Rows(i).Selected = True
End If
Next
Next
你已经做到了!
于 2012-10-12T03:44:06.907 回答