I have labels "Hardwork" and 1 datagirdview display when load form. I use the code below to do the quantity comparison in the column "TotalTime". I want if the value is in column "TotalTime"> = 30 then labels "Harwork" + 1
but not run.the result is: specified cast is not valid.
Please, help me fix it
public void BtnSearch_Click(object sender, EventArgs e)
{
db = new DbConnector();
lbTotal.Text = "00";
db.fillDataGridView("select *from tbl_WorkLoad where TimeComplete Between'" + dateTimePicker1.Value.ToString("dd-MM-yy| HH:mm:tt") + "' and '" + dateTimePicker2.Value.ToString("dd-MM-yy| HH:mm:tt") + "'", dataGridView1);
const string HardWorkLabelText = "Hard Work Count: {0}";
const int HardWorkThreshold = 30;
try
{
IEnumerable<DataGridViewRow> rows = dataGridView1.Rows.Cast<DataGridViewRow>().Where(r => ((Int32)r.Cells["TotalTime"].Value) >= HardWorkThreshold);
lbHardwork.Text = string.Format(HardWorkLabelText, rows.Count());
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
lbTotaltime.Text = (Convert.ToString(double.Parse(lbTotaltime.Text) + double.Parse(dataGridView1.Rows[i].Cells[7].Value.ToString())));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
You have apart from the exception, you have few other issues in the code. But let us focus on the issue which you reported.
From the code, I understand that, you want to display the number of hardwork and also you want to display the total hardwork time.
Since you are looping thru the rows of gridview, you can calculate both of these in the for loop.
var hardworkCount = 0;
var totalTimeSum = 0.0;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
double totalTime = double.Parse(dataGridView1.Rows[i].Cells[7].Value.ToString());
if(totalTime >= HardWorkThreshold)
{
hardworkCount++;
}
totalTimeSum += totalTime;
}
lbHardwork.Text = hardworkCount.ToString();
lbTotaltime.Text = totalTimeSum.ToString();