[英]How to change DataGridView cell color based on value of Combobox?
我有一个数据网格视图,如下所示:
我想:
表单加载时,如果Gender
列的值为Male,则Name
列对应的颜色单元格将为White
如果更改Gender
: Male → Female 列的值,则Name
列的颜色单元格为深灰色,否则,如果更改Gender
: Female → Male 列的值,则Name
列的颜色单元格为白色
我试过了,但我无法做到:
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;
}
}
或者:
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;
//}
}
关于这些的任何提示都会有很大帮助。 提前致谢。
要更改背景颜色,您必须订阅CellFormatting
事件。 然后将此代码添加到事件处理程序:
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")
{
dgv.Rows[e.RowIndex].Cells["name"].Style.BackColor = Color.White;
}
else
{
dgv.Rows[e.RowIndex].Cells["name"].Style.BackColor = Color.DarkGray;
}
}
}
要在DataGridViewComboBoxCell
选择新值时进行验证,请订阅CurrentCellDirtyStateChanged
事件并在其处理程序中尝试以下代码:
private void dataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
DataGridView dgv = sender as DataGridView;
DataGridViewCell cell = dgv.CurrentCell;
if (cell is DataGridViewComboBoxCell)
{
dgv.CommitEdit(DataGridViewDataErrorContexts.Commit);
dgv.EndEdit();
}
}
只是为了向您展示一个工作示例,我正在更改 ForeColor 而不是 Back,但概念是相同的。 您需要应用默认值:
this.dgvUsers.DefaultCellStyle.ForeColor = Color.Black;
然后根据您的触发器是什么,您需要分配一个处理程序:
dgvUsers.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.dgvUsers_CellFormatting);
this.Controls.Add(dgvUsers);
然后为了处理事件,它看起来像这样:
// Handle user going inactive or being reactivated
private void dgvUsers_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataRowView row = dgvUsers.Rows[e.RowIndex].DataBoundItem as DataRowView;
if (row != null && row.Row.ItemArray[7].Equals("N"))
{
e.CellStyle.ForeColor = Color.Gray;
}
else
{
e.CellStyle.ForeColor = Color.Black;
}
}
与接受的答案不同,这使用样式必须在一个地方更改定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.