非数据源填充DataGridView结合TextBox搜索触发对象引用错误求助
问题原因与解决方案
错误根源
触发空引用异常的核心原因有两个:
- 部分单元格的
Value为Nothing(空值),直接调用.ToString()会抛出异常 - 未绑定数据源的
DataGridView默认开启AllowUserToAddRows,最后一行是空白的待添加行,该行所有单元格值均为Nothing
修复后的代码
Private Sub btnApply_Click(sender As Object, e As EventArgs) Handles btnApply.Click Dim temp As Integer = 0 ' 清空之前的黄色高亮,避免残留 For Each row As DataGridViewRow In DataGridView1.Rows For Each cell As DataGridViewCell In row.Cells cell.Style.BackColor = DataGridView1.DefaultCellStyle.BackColor Next Next ' 遍历行时跳过最后一行的空白新行(仅当允许添加行时) For i As Integer = 0 To DataGridView1.RowCount - 1 - If(DataGridView1.AllowUserToAddRows, 1, 0) For j As Integer = 0 To DataGridView1.ColumnCount - 1 Dim cellValue As String = "" ' 先判断单元格值是否非空,再转换为字符串 If DataGridView1.Rows(i).Cells(j).Value IsNot Nothing Then cellValue = DataGridView1.Rows(i).Cells(j).Value.ToString() End If If cellValue = txtGridSearch.Text Then temp = 1 DataGridView1.Rows(i).Cells(j).Style.BackColor = Color.Yellow End If Next Next If temp = 0 Then MsgBox("Item not found") End If End Sub
关键改动说明
- 空值防护:先检查单元格
Value是否不为Nothing,再执行ToString()操作,避免空引用 - 跳过空白新行:根据
AllowUserToAddRows状态,自动跳过最后一行的空白待添加行 - 重置高亮状态:每次搜索前清空之前的黄色背景,避免历史高亮残留
内容的提问来源于stack exchange,提问作者Lord45
相关产品推荐
相关产品推荐

