簡體   English   中英

將 DataGridView 中的特定值添加到列表框(Windows 窗體/NET Framework 4.7)

[英]Add specific values from DataGridView to Listbox (Windows Forms / NET Framework 4.7)

在我的 DataGridView (DGV1) 中,我有一個包含不同字符串值 (N1-N9) 的表。 其中一些單元格值以黃色突出顯示(在表格中顯示為粗體(N1、N5、N6))。 我想將這些選定的單元格添加到列表框中,如下所示。

在此處輸入圖片說明

var foundValues = dataGridView1.Rows.Cast<DataGridViewRow>().Select(row => new
                {
                    Name = row.Cells[row.Cells.Cast<DataGridViewCell>().First(cell => cell.OwningColumn.HeaderText == "XX").ColumnIndex].Value,                    
                    ColorValue = row.Cells.Cast<DataGridViewCell>().Where(c => c.Style.BackColor == Color.Yellow).Select(cell => cell.Value.ToString()),
                    Count = row.Cells.Cast<DataGridViewCell>().Count(c => c.Style.BackColor == Color.Yellow),
                    
                }).ToArray();

                
                foreach (var s in foundValues)
                {
                    listBox1.Items.Add($"{s.Name}, {s.ColorValue}, {s.Count}");
                }

不幸的是,我的輸出包含錯誤。 黃色突出顯示的單元格值(字符串)不會顯示在 ListBox 中。

DD1, System.Linq.Enumerable + WhereSelectEnumerableIterator‘2[SystemWindows.Forms.DataGridViewCell,System.String],1
DD2, System.Linq.Enumerable + WhereSelectEnumerableIterator‘2[SystemWindows.Forms.DataGridViewCell,System.String],2
DD3, System.Linq.Enumerable + WhereSelectEnumerableIterator‘2[SystemWindows.Forms.DataGridViewCell,System.String],0


有人可以幫我嗎? 提前謝謝了!

我的 LINQ 技能充其量只是業余水平,但是從ListBox的輸出來看……

DD1, System.Linq.Enumerable + WhereSelectEnumerableIterator‘2[SystemWindows.Forms.DataGridViewCell,System.String],1

看起來第二個值是“集合”。 看看ColorValue變量是ColorValue ……

ColorValue = row.Cells.Cast<DataGridViewCell>().Where(c => c.Style.BackColor == Color.Yellow).Select(cell => cell.Value.ToString()),

這可能會返回多個值……每個值都是一個簡單的string例如“N5”和“N6”,但對象仍然是“集合”。 因此,當您執行代碼時...

listBox1.Items.Add($"{s.Name}, {s.ColorValue}, {s.Count}");

s.ColorValue是一個“集合”…… ListBox不夠聰明,無法獲取該集合並將其轉換為“單個”逗號分隔的string值。

因此,代碼需要對集合中的不同string值進行這種“組合”。 我猜有一種使用 LINQ 的方法可以做到這一點,但我的微弱嘗試失敗了,我最終使用String.Join方法來組合集合中的strings

在我的測試中,將ColorValue變量設置為連接的strings似乎可以正常工作。

我所做的更改如下使用您的代碼。 正如您所展示的,此單一更改在ListBox正確顯示了值。 當然,您可能需要稍加修改才能獲得正確的逗號位置,但這應該是微不足道的。

ColorValue = String.Join(", ", row.Cells.Cast<DataGridViewCell>().Where(c => c.Style.BackColor == Color.Yellow).Select(cell => cell.Value)),

我希望這是有道理的並有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM