首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

VB.NET DataGridView 從值為 1 的單元格開始讀取到 36:雙層循環遍歷邏輯

     編輯:程式設計綜合問答

需求理解

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

關鍵點

  • **查找起點**:雙層循環掃描整個網格,找到第一個 "1" 記錄行列索引。
  • **行優先遍歷**:外層行、內層列;首行從 startCol 開始,後續行從第 0 列開始。
  • **計數器控制**:讀滿 36 個即停止。
  • **動畫高亮**: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 線程阻塞問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved