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.