如何在datagridview vb.net中汇总所有日期时间

时间:2019-01-24 13:09:36

标签: sql vb.net

我一直想知道如何转换这行代码以计算整数之和。

我需要汇总来自datagridview的所有列数据,其格式为时间跨度(0,0,0)

我遇到错误

  

System.FormatException:'输入字符串的格式不正确。'

有什么帮助吗?

txtTotalTime.Text = 
 ( From row As DataGridViewRow In DataGridView3.Rows
   Where row.Cells(2).FormattedValue.ToString() <> String.Empty
   Select Convert.ToInt32(row.Cells(2).FormattedValue)
 ).Sum().ToString()

2 个答案:

答案 0 :(得分:1)

我希望这会有所帮助(这是另一种方法)。它与埃姆西赫尔(Amessihel)一样。

注意:如果TimeOfDay大于24小时。然后输出EX:“ 1.00:05:09”


        Dim dgvrRow As DataGridViewRow  
        Dim tsSum As TimeSpan  
        Dim tsTemp As TimeSpan          

        TimeSpan.TryParse("00:00:00", tsSum) 

        For Each row In datagridview3.rows  
            strTemp = row.Cells(2).Value.ToString  
            If strTemp <> String.Empty Then  
                tsTemp = DateTime.ParseExact(strTemp, "HH,mm,ss", Nothing).TimeOfDay  

                tsSum = tsSum.Add(tsTemp)  
            End If  
        Next  

        txtTotalTime.Text = tsSum.toString  

答案 1 :(得分:0)

Unfortunately Sum() 无法处理 TimeSpan 。因此,诀窍是:

  1. 使用自定义格式解析每个调用DateTime.ParseExact的条目(我假设您的输入是h,m,s
  2. 要将其转换为Long值的“ Ticks”。
  3. 要将Long值传递给Sum()
  4. 最后将结果转换为TimeSpan。

下面的一段代码:

Dim ts As TimeSpan = New TimeSpan(
        (From row As DataGridViewRow In DataGridView3.Rows
         Where row.Cells(2).FormattedValue.ToString() <> String.Empty
         Select DateTime.ParseExact(row.Cells(2).FormattedValue, "h,m,s", Nothing).TimeOfDay.Ticks
             ).Sum())
txtTotalTime.Text = ts.ToString

注意:Nothing作为格式提供程序在此处传递。 Globalization.CultureInfo.InvariantCulture也可以通过,效果相同。

相关问题