在datagridview中收集时间

时间:2017-12-21 09:58:32

标签: c#

在我在表格中使用双重格式之前,我可以整理列并得到结果为" Saldo"在表的末尾,我怎么能用DATETIME来做呢?

enter image description here

if (e.RowIndex == this.dataGridView1.NewRowIndex)
{
    e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Bold);
    e.CellStyle.ForeColor = Color.Red;
    switch (e.ColumnIndex)
    {
        case 0:
            //e.Value = "Saldo";
            // e.Value = benutzer;
        break;
        case 1:
            double sum = 0.0d;
            for (int i = 0; i < this.dataGridView1.NewRowIndex; i++)
            {
                var value = this.dataGridView1[1, i].Value;
                if (value is double)
                {
                    sum += ((double)value);
                }
            }
            e.Value = "Saldo: " + Math.Round(sum, 1);
        break;
        case 2:
            e.Value = benutzer;
        break;
    }
}

谢谢大家的帮助

1 个答案:

答案 0 :(得分:1)

显然,value不是双倍的,所以总和永远不会改变。 更改代码

if (value is double)
{
    sum += ((double)value);
}

if (value is TimeSpan)
{
    sum += ((TimeSpan)value).TotalHours;
}

TotalHours属性将小时数作为double类型的小数值返回,例如8.5。另请参阅Documentation of the TotalHours property

如果你想要像17:30:00这样的输出,你应该将这些值加起来像TimeSpan一样:

        case 1:
            TimeSpan sum = TimeSpan.FromHours(0.0);
            for (int i = 0; i < this.dataGridView1.NewRowIndex; i++)
            {
                var value = this.dataGridView1[1, i].Value;
                if (value is TimeSpan)
                {
                    sum += ((TimeSpan)value);
                }
            }
            e.Value = "Saldo: " + sum;
        break;