Search code examples
c#datagridviewcellpaint

DataGridView, loop through all rows with exception


Hi all I need help I want to loop trough the all cells in datagrid view and I want to check all neighboring cells around it so I need to check all directions around cell. That would be 8 directions (up,down,left,right,up-left,up-right,down-left,down-right) And I want to paint it if they are neighbors with black. Both of them.

So here is what I got for now:

for (int x = 0; x < yourGridName.Rows.Count; x++)
{
    //Loop through all cells in that row and change its color.
    for (int y = 0; y < yourGridName.Rows[x].Cells.Count; y++)
    {
        if (dataGridView1.Rows[dataGridView1.SelectedRows[x].Index].Cells[y].Value.ToString() != "YES")
         yourGridName.Rows[x].Cells[y].Style.BackColor = 
         System.Drawing.Color.Black;
    }
  }
}

Solution

  • What I understand you need to know how to get all the 8 neighbors for your X/Y grid cell.

    If you at grid cell [X][Y] then the 8 neighbors should be

    grid[X][Y-1] (if Y-1 >= 0)
    grid[X][Y+1] (if Y+1 < Cells.Count)
    grid[X-1][Y] (if X-1 >= 0)
    grid[X+1][Y] (if X+1 < Rows.Count)
    grid[X+1][Y+1] (if Y+1 < Cells.Count && X+1 < Rows.Count)
    grid[X-1][Y-1] (if Y-1 >= 0 && X-1 >= 0)