【问题标题】:Change dataGridView Cell Formatting on button click (not on cell click)在按钮单击时更改 dataGridView 单元格格式(不是在单元格单击时)
【发布时间】:2016-04-21 14:30:50
【问题描述】:

我正在为学校项目编写酒店预订管理器。我需要检查酒店的客人是否已登记入住或退房。如果客人在数据库中写入的日期没有入住或退房,我需要更改行的颜色,以标记此预订需要注意。

我正在尝试找到在单击按钮时更改单元格格式的解决方案(现在,稍后将是计划任务)。我知道如何在将数据加载到 dataGridView 时更改单元格格式。

我一直在尝试这个

dataGridView1.Rows[(int)myReader["id"]].Style.BackColor = System.Drawing.Color.LightPink;

但它说没有Style方法,我理解是因为它是来自CellFormatting Class的方法。

我可以在 CellFormatting 类中编写代码,但我不能在按钮单击时调用它,因为我不知道在 () for sender 和 e 之间写什么。

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)

【问题讨论】:

  • 最好根据排序注意myReader["id"]中的数据库ID可能与dataGridView1中的行索引不同
  • 你应该在DataGridView.Rows集合上使用循环而不是(int)myReader["id"]
  • 不久前,我意识到当我第 10 次出现超出范围异常时。已经犯过这个错误了。

标签: c# mysql winforms datagridview formatting


【解决方案1】:

您可以使用DataGridViewRowDefaultCellStyle 属性为行设置一些样式,例如:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    //if some criteria
    row.DefaultCellStyle.BackColor = Color.Red;
}

您也可以在一些合适的事件中更改样式,例如您可以 hanlde RowPrePaint 并检查该行的一些条件并更改其样式:

private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
    //you can find the row this way: this.dataGridView1.Rows[e.RowIndex]
    //then check some criteria on some cell values
    //then you can set the style for row this way:
    this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
}

【讨论】: