如何根据Combobox的值更改DataGridView单元格颜色?
我有一个datagridview如下:
我想要:
-
当表单加载时,如果
Gender
列的值为Male,则列Name
的相应颜色单元格将为White -
如果更改列的
Gender
:男性→女性,列Name
颜色单元格将为DarkGray,否则如果更改列的Gender
:女性→男性,列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
选择新值时进行validation,请订阅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; } }
与接受的答案不同,这使用样式必须在一个地方定义更改。