Guys, i'm trying to total the hours in datagridview row.cells[10] and display the total hours in Label1, the format in the cells is "00:00"
I can't seem to get the formular right though for the total hours?
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
VulpesRank #55 · 29.2K reputationPosted Apr 11, 2012, 10:18 AM EDT
// now using ints
int totalHours = 0;
int totalMins = 0;
foreach(DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow) break;
object val = row.Cells[10].Value;
if (!Convert.IsDBNull(val) && val != null && val.ToString().Length > 0)
{
string[] items = val.ToString().Split(':');
totalHours += int.Parse(items[0]);
totalMins += int.Parse(items[1]);
}
}
totalHours += totalMins/60;
totalMins = totalMins % 60;
label1.Text = String.Format("{0:D2}:{1:D2}", totalHours, totalMins);
VulpesRank #55 · 29.2K reputationPosted Apr 11, 2012, 7:58 AM EDT
Try something like this:
decimal totalHours = 0;
foreach(DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow) break;
object val = row.Cells[10].Value;
if (!Convert.IsDBNull(val) && val != null)
{
totalHours += decimal.Parse(val.ToString());
}
}
label1.Text = totalHours.ToString("F2");
mike DelvottiRank #7,298 · 244 reputationPosted Apr 11, 2012, 8:09 AM EDT
It throws the following error?
Input string was not in a correct format.
I have double checked the the string in the database and it is in the following format 00:00
VulpesRank #55 · 29.2K reputationPosted Apr 11, 2012, 8:22 AM EDT
To test for that, I'd try this modification:
decimal totalHours = 0;
foreach(DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow) break;
object val = row.Cells[10].Value;
if (!Convert.IsDBNull(val) && val != null && val.ToString().Length > 0)
{
totalHours += decimal.Parse(val.ToString());
}
}
If it still doesn't work can you put a breakpoint on this line:
totalHours += decimal.Parse(val.ToString());
and see what values are showing up in the debugger for val.ToString().
mike DelvottiRank #7,298 · 244 reputationPosted Apr 11, 2012, 8:45 AM EDT
VulpesRank #55 · 29.2K reputationPosted Apr 11, 2012, 8:56 AM EDT
label1.Text = totalHours.ToString("F2");
mike DelvottiRank #7,298 · 244 reputationPosted Apr 11, 2012, 10:52 AM EDT