2

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)

Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178
genespos
  • 3,211
  • 6
  • 38
  • 70

1 Answers1

2

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

Community
  • 1
  • 1
Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178
  • I've declared `RowStrList` this way because I need it only here. Anyway I'll check my code to be sure that everything works as espected. Thanks – genespos Sep 27 '16 at 15:20
  • Yes, if you just need it in the block to create that string, you are fine - it wasnt clear if that was all it was intended for. – Ňɏssa Pøngjǣrdenlarp Sep 27 '16 at 15:22