Pick 2-column value in Gridview to perform calculation

Asked

Viewed 2,159 times

0

I am developing a simple Input/Output system of users in an environment and I have a Grid with some data and among them 2 fields of type Datetime, being them Input and Output.

I need to take the values of these fields of ALL LINES of my Grid and then perform a calculation to know the user’s permanence in the place (permanence = output - input), however I am not able to capture the data of these two columns row by row.

Column 4 is the Input column and Column 6 of Output.

Note: All the code is inside a button.

Follows my code:

private void btCalcPermanencia_Click(object sender, EventArgs e)
{
    DateTime ent = new DateTime();
    DateTime saida = new DateTime();
    TimeSpan permanencia = new TimeSpan();

    for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
    {
        ent = Convert.ToDateTime(dataGridView1.SelectedRows[i].Cells[4].Value);
        saida = Convert.ToDateTime(dataGridView1.SelectedRows[i].Cells[6].Value);
        permanencia = saida - ent;
        dataGridView1.Columns.Add(permanencia.ToString(), "Permanencia");
    }

}

1 answer

1


Your error is happening because you are only taking the values of the selected lines, change SelectedRows for Rows

Note. Inside the Loop, the command dataGridView1.Columns.Add(permanencia.ToString(), "Permanencia"); will add a new column for each row that is traversed, Create the column before the loop, and just place its Value:

dataGridView1.Columns.Add("colunaPermanencia", "Permanencia");
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    ent = Convert.ToDateTime(dataGridView1.Rows[i].Cells[4].Value);
    saida = Convert.ToDateTime(dataGridView1.Rows[i].Cells[6].Value);
    permanencia = saida - ent;
    dataGridView1.Rows[i].Cells["colunaPermanencia"].Value = permanencia.ToString();
}

And take off the -1 of for because if not, the last line will not be covered

  • It worked. Thank you very much. I really appreciate...

  • Welcome to the community, mark as answer please =] is the V just below the evaluation of the answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.