locked
DataGridView row and column color

    Question

  • Hi all,

    I use CellClick event for highlight row and column where mouse click occur. For example if clic occur in row 3, column 5, I set row #3 and column #5 color to yellow. Then if another clic occur I need to change color of all cell and highlight new row and column. The only way I found for getback to default color is to write a new color in all row with for instruction. But, by doing this, I can't highlight any column.

    So first clic work perfect, second clic I only get a row highlighted. I know row color have priority, how to remove color set by previous clic? I tried

    ...DefaultCellStyle.BackColor =

    null;.....not working.

    thanks

    Wednesday, April 20, 2011 3:25 AM

Answers

  • You can do it like this:

    foreach(DataGridViewRow row in dgv.Rows)
    {
      if(row.Index == e.RowIndex)
      {
        foreach(DataGridViewCell cell in row.Cells)
        {
          if(cell.ColumnIndex == e.ColumnIndex) //or cell.Columnindex == dgv.CurrentCell.ColumnIndex)
             dgv.DefaultCellStyle.BackColor = Color.Yellow
           else
             dgv.DefaultCellStyle.BackColor = Color.White //or what ever!
        }
      }
    }

     

    Instead of cell.Columnindex can be cell.index (Im not sure now, I wrote this code by heart)

    But hope it helps,

     


    Mitja
    • Marked as answer by slcman Thursday, April 21, 2011 2:28 AM
    Wednesday, April 20, 2011 8:19 AM

All replies

  • Hello

    I am hoping you will kindly take a look at. Here is the link  

    http://forums.microsoft.com/Forums/ShowPost.aspx?PostID=4129737&SiteID=1

    Thanks

     


    Sankarshan Parida.Please mark the post answered your question as the answer, and mark other helpful posts as helpful, so they will appear differently to other users who are visiting your thread for the same problem.
    Wednesday, April 20, 2011 5:15 AM
  • You can do it like this:

    foreach(DataGridViewRow row in dgv.Rows)
    {
      if(row.Index == e.RowIndex)
      {
        foreach(DataGridViewCell cell in row.Cells)
        {
          if(cell.ColumnIndex == e.ColumnIndex) //or cell.Columnindex == dgv.CurrentCell.ColumnIndex)
             dgv.DefaultCellStyle.BackColor = Color.Yellow
           else
             dgv.DefaultCellStyle.BackColor = Color.White //or what ever!
        }
      }
    }

     

    Instead of cell.Columnindex can be cell.index (Im not sure now, I wrote this code by heart)

    But hope it helps,

     


    Mitja
    • Marked as answer by slcman Thursday, April 21, 2011 2:28 AM
    Wednesday, April 20, 2011 8:19 AM
  • I was thinking a method exist for remove all previous set color and return all to grid default. Once I change a row color I cannot use Column color property...!?!?

    Wednesday, April 20, 2011 1:41 PM