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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Apr 11, 2012, 2:18 PM
// 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);
mike DelvottiPosted Apr 11, 2012, 2:52 PM
VulpesPosted Apr 11, 2012, 12:56 PM
label1.Text = totalHours.ToString("F2");
mike DelvottiPosted Apr 11, 2012, 12:45 PM
VulpesPosted Apr 11, 2012, 12:22 PM
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 DelvottiPosted Apr 11, 2012, 12:09 PM
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
VulpesPosted Apr 11, 2012, 11:58 AM
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");