2
votes

I have a DataGridView that uses a DataTable as datasource.

I need to get (as array of string) the values shown in the DataGridView with the same format.

So, in the DataTable there is a field with value "100" shown in the DGV as "€ 100,00". I need to get "€ 100,00" as string

Another field is a double and its value is "31.506849315068493150684931507" shown in the DGV as "€ 31,51". I need to get "€ 31,51" as string

The DataTable has fields of various type (string, date, double) and for all of them I need to get a string as shown in the DGV.

I've tried with the below code but I get values of the DataTable.

For x As Integer = 0 To Me.DGV_IntCalc.RowCount - 1
    Dim RowStrList As New List(Of String)
    For Each Col As String In MaxColLen.Keys
        RowStrList.Add(Me.DGV_IntCalc.Item(Col, x).Value.ToString)
    Next
    Calc_Summay &= String.Format(F_Str, RowStrList.ToArray) & vbCrLf
Next

F_Str is a string that gives columns format like "{0,10} {1,20}"

EDIT2:

I also tried:

RowStrList.Add(Format(Me.DGV_IntCalc.Item(Col, x).Value, _
               Me.DGV_IntCalc.Columns(Col).DefaultCellStyle.Format))

but it didn't give expected result. I also tried:

Dim Str$ = Me.DGV_IntCalc.Item(Col, x).Value.ToString
Dim Frmt$ = Me.DGV_IntCalc.Columns(Col).DefaultCellStyle.Format
Dim FormattedStr$ = Format(Str, Frmt)

or

Dim FormattedStr$ = String.Format(Str, Frmt)

But I get values as in the DataTable (not formatted)

1
Why don't u simply use .Value instead of .Value.toString ? - noidea
You've got your arguments to String.Format transposed in your edit. - Andrew Morton
@AndrewMorton I tried both Format and String.Format with respective syntax but I'm still getting errors. - genespos
@genespos I can't see the error messages on your screen from over here. - Andrew Morton
@AndrewMorton I don't get runtime errors I get wrong results: I get values as in the DataTable or sometimes get Format string (i.e. "p2") instead of the value - genespos

1 Answers

2
votes

The DGV provides a view of the data which includes formatting. Somewhere you tell it to format that one column as currency. Maybe something like this:

dgv1.Columns(3).DefaultCellStyle.Format = "C2"

To get back those formatted values, use the FormattedValue property:

For n As Int32 = 0 To dgv1.Rows.Count - 1
    Console.WriteLine(dgv1.Item(n, 3).FormattedValue)
Next

Also note that in your code, you declare your List inside the If:

For x As Integer = 0 To Me.DGV_IntCalc.RowCount - 1
    Dim RowStrList As New List(Of String)
    For Each Col As String In MaxColLen.Keys
        RowStrList.Add(Me.DGV_IntCalc.Item(Col, x).Value.ToString)
    Next
    Calc_Summay &= String.Format(F_Str, RowStrList.ToArray) & vbCrLf
Next

Since RowStrList is declared inside the If block, it will only exist there. Everything which results in indentation also creates a new Block Scope. See: Reference variables and objects elsewhere for more info