问题
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