c# - 如何将 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}"));
解决方案
我将遍历您的 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
的内容更加直观,并且可以让您轻松地将相同的模式用于其他事情。
推荐阅读
- pytorch - Pytorch 语义分割损失函数
- api - 是否可以获得按最佳匹配排序的多个结果?
- python - 关于 lambda 函数
- r - R 规则:如何将因素与交易联系起来?
- apache-kafka - java.io.IOException:无法将语句写入 batch_layer.test。最新的例外是 Key may not be empty
- latex - 在 Mediawiki 数学扩展中设置处理 unicode
- python - 如何用多个连续的 Conv2D 层替换 keras 中的 Conv2D 层?
- c# - 虚幻 4:让 Windows 插件在 Linux 上运行
- javascript - Vuetify v-btn :href 下载在浏览器中打开 XML 而不是下载
- python - 根据特定值重命名多个熊猫 DataFrame 值