@Gerald Oakham , Welcome to Micrososoft Q&A, based on my test, I almost reproduced your problem.
Please make the following changes:
First, Please don't use the varibale that starts with the number, it is Irregular. Please try to use Counter
to replace it.
Second, Please add one to the counter after you color the current row.
Here is a code example you could refer to.
private void button1_Click(object sender, EventArgs e)
{
int Counter = 0;
foreach (DataGridViewRow item in dataGridView1.Rows)
{
if (item.Cells["user_password"].Value.ToString().Contains("123"))
{
dataGridView1.Rows[Counter].Cells[1].Style = new DataGridViewCellStyle { ForeColor = Color.Red };
Counter++;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
TestEntities context=new TestEntities();
dataGridView1.DataSource = context.tbl_User.OrderBy(x => x.user_id).ToList();
}
If you click the button, you will see the related cells is colored.
Best Regards,
Jack
If the answer is the right solution, please click "Accept Answer" and 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.