Hi @ankit goel , Welcome to Microsoft Q&A.
When entering a cell, change the background color of the cell to black, the foreground color to white, and the background color of other cells in the row to yellow. Record the position of the cell. When the row of the cell has not changed, but the column has changed: change the background color of the previous cell to yellow, and the current background color to black. When the cell row changes: change the background color of the previous row to white, and the background color of the current position to black.
using System.Drawing;
using System.Windows.Forms;
namespace _7_5_x
{
public partial class Form1 : Form
{
private int previousRowIndex = -1;
private int previousColumnIndex = -1;
public Form1()
{
InitializeComponent();
}
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex >= 0 && (e.RowIndex != previousRowIndex || e.ColumnIndex != previousColumnIndex))
{
RestorePreviousCellStyles();
SetCurrentCellStyles(e.RowIndex, e.ColumnIndex);
UpdatePreviousIndices(e.RowIndex, e.ColumnIndex);
HighlightCurrentRow(e.RowIndex);
}
}
private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
RestoreCellStyles(e.RowIndex, e.ColumnIndex);
}
}
private void RestorePreviousCellStyles()
{
if (previousRowIndex >= 0 && previousColumnIndex >= 0)
{
for (int colIndex = 0; colIndex < dataGridView1.Columns.Count; colIndex++)
{
dataGridView1.Rows[previousRowIndex].Cells[colIndex].Style.BackColor = Color.White;
}
}
}
private void SetCurrentCellStyles(int rowIndex, int columnIndex)
{
dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Black;
dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.ForeColor = Color.White;
}
private void UpdatePreviousIndices(int rowIndex, int columnIndex)
{
previousRowIndex = rowIndex;
previousColumnIndex = columnIndex;
}
private void HighlightCurrentRow(int rowIndex)
{
for (int colIndex = 0; colIndex < dataGridView1.Columns.Count; colIndex++)
{
if (colIndex != previousColumnIndex)
{
dataGridView1.Rows[rowIndex].Cells[colIndex].Style.BackColor = Color.Yellow;
}
}
}
private void RestoreCellStyles(int rowIndex, int columnIndex)
{
dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = dataGridView1.DefaultCellStyle.BackColor;
dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.ForeColor = dataGridView1.DefaultCellStyle.ForeColor;
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.