【发布时间】:2019-03-20 07:40:26
【问题描述】:
我正在开发基于访问权限的 WinForm 应用程序。我的 DataGridView 中有彩色单元格(DateColumn)。我正在尝试计算如图所示的彩色单元格,并希望在标签的文本上反映彩色单元格的总数。我尝试了下面的代码,这些代码不计算我的 DataGridView 的彩色单元格总数,尽管计算总行数。具体问题可以通过this图片理解
我的代码如下:
private void metroGrid1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (this.metroGrid1.Columns[e.ColumnIndex].DataPropertyName == "Date 1")
try
{
var EMIDate1 = Convert.ToDateTime(metroGrid1.Rows[e.RowIndex].Cells["date1DataGridViewTextBoxColumn"].Value);
for (int i = 0; i < metroGrid1.RowCount; i++)
{
if (EMIDate1 <= DateTime.Today)
{
int countDarkRed = 0;
e.CellStyle.BackColor = Color.DarkRed;
e.CellStyle.ForeColor = Color.White;
foreach (DataGridViewRow row in this.metroGrid1.Rows)
{
if (row.Cells["date1DataGridViewTextBoxColumn"].Style.BackColor == Color.DarkRed)
{
countDarkRed++;
}
}
labelEMI.Text = "Total EMI due as on today:" + countDarkRed;
}
}
}
catch
{
}
}
【问题讨论】:
-
到底是什么问题?你希望有
countDarkRed = 1,但它是0? -
我不明白你想要什么。你想计算有多少细胞有深红色背景吗?为什么不设置颜色的时候加个计数器呢?
-
@NoChance 我想计算所有深红色单元格,还需要在 label.text 上显示这个数字 & 无法理解这一行的含义“为什么在设置颜色时不添加计数器?”。
-
@GiulioCaccin 我的问题是我无法计算所有深红色,你能告诉我为什么我应该有 countDarkRed = 1 尽管 DataGridView 开始时没有任何深红色单元格。
-
最简单的方法是在更改单元格颜色时增加计数器,而不是计算彩色单元格。
标签: c# datagridview