首页 > 解决方案 > 如何将 DataGridView 的颜色值传递给 ListBox?

问题描述

如何将彩色单元格 (DGV1 = DataGridView1)) 的值传递给 ListBox?在上面的插图示例中,只有一个彩色单元格被传输到 ListBox。但是如何将所有彩色单元格的值从 DataGridView 传输到 ListBox(参见 DGV2)?谢谢大家的帮助!

var YellowCell = dataGridView1.Rows.Cast<DataGridViewRow>().Select(row => new
{
    nameCol = row.Cells[row.Cells.Cast<DataGridViewCell>().First(cell => cell.OwningColumn.HeaderText == "XX").ColumnIndex].Value,
    
    coloredCells = row.Cells.Cast<DataGridViewCell>().First(c => c.Style.BackColor == Color.Yellow).Value,
}).ToList();

YellowCell.ForEach(s => listBox1.Items.Add($"{s.nameCol} : { s.coloredCells}"));

在此处输入图像描述

标签: c#

解决方案


我将遍历您的 DataGridView 行并在该循环中遍历单元格,然后在单元格值与您设定的条件匹配时将其添加到集合中(在本例中BackColor == Color.Yellow)。

例如:

var yellowCellValues = new List<string>(); //the type should be whatever is in your dgv

foreach(DataGridViewRow row in dataGridView1.Rows)
{
    foreach(DataGridViewCell cell in row.Cells)
    {
        if (cell.Style.BackColor == Color.Yellow)
        {
            yellowCellValues.Add(cell.Value.ToString());
        }
    }
}

您可能可以在 LINQ 语句中执行此操作,但如果您不熟悉 LINQ,我认为上面foreach的内容更加直观,并且可以让您轻松地将相同的模式用于其他事情。


推荐阅读