如何按背景色求和

时间:2019-04-23 10:13:18

标签: c# datagridview

在每一行中,单元格均以背景色突出显示(每行三个名称)。我想要背景颜色(而不是单元格内容)的值总和。即使经过各种尝试,我也不得不承认我不知道如何用名字(老师,学生)和ListBox中每一行的总和来填充ListBox(请参见以下代码…)总和为3,则ListBox中的条目应与相应的名称一起显示。 ListBox中的结果应如下所示:

3; Teacher
3; Students 

int sum = 0; 
{
   for (int i = 0; i <= dataGridView2.Columns.Count - 1; i++)
   {
      sum += Convert.ToInt32(dataGridView2.Rows[0].Cells[i].Style.BackColor == Color.YellowGreen);

      if (sum == 3)
      {
         sum++;
         listBox9.Items.Add(sum);
         listBox9.ForeColor = Color.DarkCyan;
         listBox9.Font = new Font("Georgia", 16);

DGV with 3 Cells highlighted per row and a ListBox

1 个答案:

答案 0 :(得分:0)

我认为这可以满足您的要求。对于每一行,它将对所有具有黄色绿色背景色的单元格进行计数,并关联行名称(即,示例中的名称为“老师”和“学生”,如标题为“ DD”的列中所示)。

// Setup the DataGridView as in your example
var dgv = new DataGridView();
dgv.Columns.Add("s1", "s1");
dgv.Columns.Add("s2", "s2");
dgv.Columns.Add("s3", "s3");
dgv.Columns.Add("s4", "s4");
dgv.Columns.Add("s5", "s5");
dgv.Columns.Add("s6", "s6");
dgv.Columns.Add("DD", "DD");    
dgv.Rows.Add("Fiona", "Lila", "Ben", "Ella", "Leon", "John", "Teachers");
dgv.Rows.Add("Jack", "Luke", "Fiona", "Sophie", "Lila", "Leon", "Students");
dgv.AllowUserToAddRows = false;
dgv.Rows[0].Cells[0].Style.BackColor = Color.YellowGreen;
dgv.Rows[0].Cells[1].Style.BackColor = Color.YellowGreen;
dgv.Rows[0].Cells[4].Style.BackColor = Color.YellowGreen;
dgv.Rows[1].Cells[2].Style.BackColor = Color.YellowGreen;
dgv.Rows[1].Cells[4].Style.BackColor = Color.YellowGreen;
dgv.Rows[1].Cells[5].Style.BackColor = Color.YellowGreen;

// Query the DataGridView, counting each row's cells with the YellowGreen background color, correlating with the row name stored in the DD column
var sums = dgv.Rows.Cast<DataGridViewRow>()
    .Select(row => new { 
        Name = row.Cells[row.Cells.Cast<DataGridViewCell>().First(cell => cell.OwningColumn.HeaderText == "DD").ColumnIndex].Value , 
        Count = row.Cells.Cast<DataGridViewCell>().Count(c => c.Style.BackColor == Color.YellowGreen)})
    .ToList();

// Add the counts for each row to the ListView
var lb = new ListBox();
sums.ForEach(s => lb.Items.Add($"{s.Name}: {s.Count}"));