How to Save DataGridView FormatedValue?

aman_VB

Member
Joined
Apr 27, 2010
Messages
23
Programming Experience
1-3
Hi all,

I am able to open/read/write/save DataGridView. But if I try to format the cells and fonts and save them, it just saves them in plain text. how do you save the formated value of dgv cells?

Thanks in advance
VB.NET:
'--------------Save DataGridView data----------------

        Dim fs As FileStream = New FileStream(filePath, FileMode.Create)
        Dim sw As StreamWriter = New StreamWriter(fs)

        Dim I As Integer = 0
        Dim j As Integer = 0
        Dim cellvalue$
        Dim rowLine As String = ""
        Try
            For j = 0 To (DataGridView1.Rows.Count - 2)
                For I = 0 To (DataGridView1.Columns.Count - 1)
                    If Not TypeOf DataGridView1.CurrentRow.Cells.Item(I).Value Is DBNull Then
                        cellvalue = DataGridView1.Item(I, j).FormattedValue.ToString
                    Else
                        cellvalue = ""
                    End If
                    rowLine = rowLine + cellvalue + ","
                Next
                sw.WriteLine(rowLine)
                rowLine = ""
            Next
            sw.close()
        Catch ex As Exception
            MessageBox.Show("Error occured while writing to the file." + e.ToString())
        End Try

        '---------Read file (after customizing OpenFileDialog)---------------

        Dim MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(openFileDialog1.OpenFile())

        MyReader.TextFieldType = FileIO.FieldType.Delimited
        MyReader.SetDelimiters(",")
        Dim currentRow As String()
        Dim currentField As String

        While Not MyReader.LineNumber = 5
            Try

                currentRow = MyReader.ReadFields
                With Me.DataGridView1.Rows
                    .Add(currentRow)
                End With
            Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                MsgBox("Line " & ex.Message & _
                  "is not valid and will be skipped.")

            End Try
        End While
 	Catch ex As Exception
            MsgBox(ex.Message & "The file is corrupt")
        End Try

        If (MyReader IsNot Nothing) Then
            MyReader.Close()

        End If
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,726
Location
Sydney, Australia
Programming Experience
10+
Just like pretty much every other control, formatting in a DataGridView is a property of the control, not of the data in the control. The exception to that rule is the RichTextBox. If you actually want to be able to store formatting information with data then you'd need to create a custom cell and column with RichTextBox functionality, which would not be easy. The alternative is to store the formatting information separate to the data itself, which you can do in any way you see fit.
 
Top Bottom