gpt4 book ai didi

c# - 如何根据 Combobox 的值更改 DataGridView 单元格颜色?

转载 作者:行者123 更新时间:2023-11-30 15:20:37 24 4
gpt4 key购买 nike

我有一个数据 GridView 如下:

enter image description here

我愿意:

  • 加载表单时,如果 Gender 列的值为 Male,则 Name 列对应的颜色单元格将为 White

  • 如果更改 Gender 列的值:Male → Female,Name 列的颜色单元格将为 DarkGray,否则,如果更改 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();
}
}

关于c# - 如何根据 Combobox 的值更改 DataGridView 单元格颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39726738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com