genespos genespos - 2 months ago 11
Vb.net Question

Get string as shown in DataGridView

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)

Answer

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

Comments