DataGridView 中數據按行列排布(如日曆),需從**內容為 "1" 的單元格開始**,按行優先順序依次讀取到 "36"。並高亮顯示讀取路徑(動畫效果)。
Dim startRow As Integer = -1, startCol As Integer = -1
' 1. 查找值為 "1" 的單元格位置
For i As Integer = 0 To DataGridView1.Rows.Count - 1
For j As Integer = 0 To DataGridView1.Columns.Count - 1
If DataGridView1.Rows(i).Cells(j).Value IsNot Nothing AndAlso
DataGridView1.Rows(i).Cells(j).Value.ToString() = "1" Then
startRow = i
startCol = j
Exit For
End If
Next
If startRow >= 0 Then Exit For
Next
If startRow = -1 Then
MessageBox.Show("未找到起始值 1")
Return
End If
' 2. 從起點開始行優先遍歷,讀取 36 個值
Dim count As Integer = 0
For i As Integer = startRow To DataGridView1.Rows.Count - 1
Dim colStart As Integer = If(i = startRow, startCol, 0)
For j As Integer = colStart To DataGridView1.Columns.Count - 1
Dim cell = DataGridView1.Rows(i).Cells(j)
Dim val = If(cell.Value IsNot Nothing, cell.Value.ToString(), "")
' 處理值...
Console.WriteLine($"讀取: Row={i}, Col={j}, Val={val}")
' 動畫高亮(可選)
cell.Style.BackColor = Color.Yellow
Application.DoEvents()
Threading.Thread.Sleep(200)
cell.Style.BackColor = Color.White
count += 1
If count >= 36 Then Exit For
Next
If count >= 36 Then Exit For
Next
startCol 開始,後續行從第 0 列開始。cell.Style.BackColor + Application.DoEvents() + Thread.Sleep 實現可視化步進(UI 線程會卡頓,生產環境建議用 Timer/Task+Invoke)。若 "1" 到 "36" 不在連續單元格,而是散落,需先收集所有單元格按值排序:
Dim cells = New List(Of DataGridViewCell)()
For Each row As DataGridViewRow In DataGridView1.Rows
For Each cell As DataGridViewCell In row.Cells
If cell.Value IsNot Nothing AndAlso IsNumeric(cell.Value) Then
cells.Add(cell)
End If
Next
Next
cells.Sort(Function(a, b) Integer.Parse(a.Value).CompareTo(Integer.Parse(b.Value)))
' 取前 36 個...
DataGridView 從指定值開始順序讀取:先雙層循環定位起點,再行優先遍歷配合計數器。動畫高亮用 Cell.Style.BackColor 切換,注意 UI 線程阻塞問題。