How to sum Time from a DataGridView Columns

一个人想着一个人 提交于 2021-02-08 08:59:22

问题


I have a DataGrid with a time column that I need to sum to get the total time, but I can't get that! I'm using this code to try the time sum, with Linq:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    textBox8.Text = dataGridView1.Rows.Cast<DataGridViewRow>()
                                 .AsEnumerable()
                                 .Sum(x => decimal.Parse(x.Cells["Duracao"].Value.ToString()))
                                 .ToString();
}

Can anybody help me here? Regards


回答1:


Have a look at below code sample. May be it will help you :

private void BindGrid()
{
    // Bind Grid
    var times = new List<Info>();
    times.Add(new Info(){ Time = "0:3:5" });
    times.Add(new Info() { Time = "0:2:10" });
    times.Add(new Info() { Time = "1:15:30" });
    this.dataGridView1.DataSource = times;

    // Retrieve total seconds
    double seconds = 0;
        seconds = dataGridView1.Rows.Cast<DataGridViewRow>()
            .AsEnumerable()
            .Sum(x => TimeSpan.Parse((x.Cells["Time"].Value.ToString())).TotalSeconds);

    // Assign to textbox
    textBox8.Text = TimeSpan.FromSeconds(seconds).Hours + ":" + TimeSpan.FromSeconds(seconds).Minutes
            + TimeSpan.FromSeconds(seconds).Seconds;
}

Info Class:

public class Info
{
    public string Time { get; set; }
}


来源:https://stackoverflow.com/questions/25013073/how-to-sum-time-from-a-datagridview-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!