I have a datagridview as below:
I would like:
When the form load, if the
Gender
column's value is Male, the corresponding color cell of columnName
will be WhiteWhen if changes the value of the column
Gender
: Male → Female, color cell of the columnName
will be DarkGray, otherwise if changes the value of the columnGender
: Female → Male, color cell of the columnName
will be White
I tried it but I am not able to do it:
private void dataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
DataGridView dgv = sender as DataGridView;
DataGridViewCell cell = dgv.CurrentCell;
if (dgv.Rows[cell.RowIndex].Cells["Gender"].Value.ToString().Trim() == "Male")
{
// Male
dgv.Rows[cell.RowIndex].DefaultCellStyle.BackColor = Color.White;
}
else
{
// Female
dgv.Rows[cell.RowIndex].DefaultCellStyle.BackColor = Color.DarkGray;
}
}
OR:
private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridView dgv = sender as DataGridView;
if (dgv.Columns[e.ColumnIndex].Name.Equals("Gender"))
{
if (e.Value != null && e.Value.ToString().Trim() == "Male")
{
e.CellStyle.BackColor = Color.White;
}
else
{
e.CellStyle.BackColor = Color.DarkGray;
}
}
//if (dgv.Rows[e.RowIndex].Cells["Gender"].Value.ToString().Trim() == "Male")
//{
// e.CellStyle.BackColor = Color.White;
//}
//else
//{
// e.CellStyle.BackColor = Color.DarkGray;
//}
}
Any tips on these will be great help. Thanks in advance.
Just to show you a working example, I am changing ForeColor instead of Back, but the concept is the same. You need to apply a default:
Then based on what your trigger is, you need to assign a handler:
Then to handle the event, it will look something like this:
Unlike the accepted answer, this uses styles to have to change defined in a single place.
To change the Background color you must subscribe to the
CellFormatting
event. Then add this code to the event handler:To cause a validation when a new value is selected in your
DataGridViewComboBoxCell
,subscribe to theCurrentCellDirtyStateChanged
event and try this code in its handler: