这是我将数据网格视图中的值保存到文本文件的代码:
Private Sub TextFileToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles TextFileToolStripMenuItem.Click
Dim filename As String = String.Empty
Dim sfd1 As New SaveFileDialog()
sfd1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
sfd1.FilterIndex = 2
sfd1.RestoreDirectory = True
sfd1.Title = "Save Text File"
If sfd1.ShowDialog() = DialogResult.OK Then
If sfd1.FileName = String.Empty Then
MsgBox("Please input filename")
Else
filename = sfd1.FileName.ToString
Saveto_TextFile(dvList, filename)
End If
End If
End Sub
Sub Saveto_TextFile(ByVal dvList As DataGridView, ByVal filename As String)
Dim numCols As Integer = dvList.ColumnCount - 1
Dim numRows As Integer = dvList.RowCount
Dim strDestinationFile As String = "" & filename & ".txt"
Dim tw As TextWriter = New StreamWriter(strDestinationFile)
For dvRow As Integer = 0 To numRows - 1
'checking if the checkbox is checked, then write to text file
If dvList.Rows(dvRow).Cells.Item(0).Value = True Then
tw.Write("True")
tw.Write(", ")
Else
tw.Write("False")
tw.Write(", ")
End If
'write the remaining rows in the text file
For dvCol As Integer = 1 To numCols
tw.Write(dvList.Rows(dvRow).Cells(dvCol).Value)
If (dvCol <> numCols) Then
tw.Write(", ")
End If
Next
tw.WriteLine()
Next
tw.Close()
End Sub
此代码运行良好,但我唯一担心的是我将数据网格视图的属性设置为Numeric
小数点后 2 位。当我将它保存到文本文件时,它会删除小数位。
我该怎么做才能保留文本文件中的小数位?