【问题标题】:Get string as shown in DataGridView获取DataGridView中显示的字符串
【发布时间】:2016-09-27 09:07:42
【问题描述】:

我有一个使用 DataTable 作为数据源的 DataGridView。

我需要(作为字符串数组)以相同格式获取 DataGridView 中显示的值。

因此,在 DataTable 中有一个值为“100”的字段,在 DGV 中显示为“€ 100,00”。我需要将“€ 100,00”作为字符串

另一个字段是双精度值,其值为“31.506849315068493150684931507”,在 DGV 中显示为“€ 31,51”。我需要将“€ 31,51”作为字符串

DataTable 具有各种类型的字段(字符串、日期、双精度),对于所有这些字段,我需要获取 DGV 中所示的字符串。

我已尝试使用以下代码,但我得到了 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 是一个字符串,它提供类似“{0,10} {1,20}”的列格式

EDIT2:

我也试过了:

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

但它没有给出预期的结果。我也试过了:

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

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

但我得到了DataTable 中的值(未格式化)

【问题讨论】:

  • 你为什么不简单地使用.Value 而不是.Value.toString
  • 您已在编辑中转置了对 String.Format 的论点。
  • @AndrewMorton 我尝试了 FormatString.Format 各自的语法,但我仍然遇到错误。
  • @genespos 我在你的屏幕上看不到错误信息。
  • @AndrewMorton 我没有得到运行时错误 我得到错误的结果:我得到了 DataTable 中的值,或者有时得到的是格式字符串(即“p2”)而不是值

标签: .net vb.net datagridview


【解决方案1】:

DGV 提供了包括格式化在内的数据视图。您在某处告诉它将该列格式化为货币。也许是这样的:

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

要取回这些格式化值,请使用FormattedValue 属性:

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

另请注意,在您的代码中,您在 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

由于RowStrList 是在If 块内声明的,它只会存在于那里。导致缩进的所有内容也会创建一个新的块作用域。请参阅:Reference variables and objects elsewhere 了解更多信息

【讨论】:

  • 我以这种方式声明了RowStrList,因为我只在这里需要它。无论如何,我会检查我的代码以确保一切正常。谢谢
  • 是的,如果您只需要在块中使用它来创建该字符串,那很好 - 不清楚这是否就是它的全部用途。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多