简体   繁体   中英

Change color in dataGridView cell

I want to change the ForeColor in the cell when the text is not in the correct format, I have this code to change the color after the text is entered - is this the right way?

private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
     dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Red;
}

And how can I change it back after the user enters text in the correct format?

您可以在CellValidated事件处理程序中将颜色设置回正常。

Or better use dgv_CellValidating event. If the value is not the one you want, call the code you have up there. And there you must have anoher event (dgv_CellEndEdit), where you set the ForeColor back to defualt one (so error will kinda dissapear).

your code seems to be correct, if you are getting the desired visual effect you should be good to go.

same way we can change the background color also..

dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Green;

dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Green;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM