1

I am taking some columns from a SQL database and using them to populate a gridview with bound columns. Some of the columns contain a date item.

I am trying to go through each cell in a column and test the date entered against today's date. If the dates match then the cell text should read "Complete", if they don't then it should read "Not Complete".

The snag I am having is that when testing if they match, I can change the text of those which do, however when going into the else statement to change the rest, ALL cells change. I have tried an explicit if, else if as well as reversing the order of the tests. My initial thought is that the cells were being changed as desired, but on the second test each row was being looped through again but all is within the foreach loop.

 protected void equipmentGV_RowDataBound(object sender, GridViewRowEventArgs e)
    {
  
        foreach (GridViewRow row in equipmentGV.Rows)
        {

            if (row.Cells[1].Text == DateTime.Today.ToString())
            {
                row.Cells[1].Text = "Complete";
            }
            else { row.Cells[1].Text = "Not Complete"; }
        }

The outcome above is that ALL cells in the second column == "Not Complete", even those with today's date, but when the else statement is removed, today's entry's show "Complete" as desired.

  • 2
    You don't need to iterate all the rows every time. e.row contains the row that has just been bound. So you can remove the "for" part. I don't know if that fixes it, but your code would run faster :) – theGleep Oct 27 '17 at 20:52
  • 1
    Because of the `for` being executed per row, on the first row it sets all of the rows for today to `"Complete"` then on the second row no row matches today any more so it sets all rows to `"Not Complete"`. Remove the `for`. – NetMage Oct 27 '17 at 20:59

1 Answers1

0

The below answer from theGleep did indeed fix my issue

"You don't need to iterate all the rows every time. e.row contains the row that has just been bound. So you can remove the "for" part. I don't know if that fixes it, but your code would run faster :) "