Get value of 2 columns in GridView to perform calculation

0

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

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

Column 4 is the Input column and Output column 6.

Note: All code is inside a button.

Follow 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");
    }

}
    
asked by anonymous 20.05.2017 / 20:25

1 answer

1

Your error is occurring because you are getting the values of only the selected rows, change SelectedRows to Rows

Obs. Inside the Loop, the dataGridView1.Columns.Add(permanencia.ToString(), "Permanencia"); command will add a new column for each line you run, Create the column before the loop, and just put the Value of it:

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 the -1 of for because if not, the last line will not be traveled

    
20.05.2017 / 20:32