ListViewItem为空问题:MySQL users表填充ListView失败排查
修复方案
1. 完善仓储层的异常与空值处理
原仓储层代码未处理dttable为Nothing的情况,且异常捕获仅输出简单消息,无法定位users表的问题。修改后代码:
If IsNothing(tableName) Then MessageBox.Show("Please enter a table name.") Return Nothing Else Try MySqlConn.Open() sqlstr = "SELECT * FROM " & tableName & ";" dttable = MysqlClient.DataHandler.GetDataTable(sqlstr, conn, True) If Not IsNothing(dttable) Then If dttable.Rows.Count > 0 Then MessageBox.Show("table is filled!") Return dttable Else MessageBox.Show("table is empty!") Return Nothing End If Else ' 新增:处理DataTable为空的情况 MessageBox.Show($"Failed to fetch data from {tableName}: DataTable is null") Return Nothing End If Catch ex As Exception ' 输出完整异常信息,包含堆栈跟踪便于排查 MessageBox.Show($"Error accessing {tableName}: {ex.Message}{Environment.NewLine}{ex.StackTrace}") Return Nothing Finally ' 确保数据库连接始终关闭,避免资源泄漏 If MySqlConn.State = ConnectionState.Open Then MySqlConn.Close() End If End Try End If
2. 修复ListView填充代码的空引用漏洞
当repo.displayHistory()返回Nothing时,原代码直接调用table.CreateDataReader会引发空引用,进而导致ListViewItem实例化失败。同时优化空值判断逻辑(直接用DBNull.Value判断更准确):
Dim table As DataTable = repo.displayHistory() Dim nullPlaceholder As String = "null" ' 先验证table的有效性 If table IsNot Nothing AndAlso table.Rows.Count > 0 Then Dim dr As DataTableReader = table.CreateDataReader Do While dr.Read ' 确保ID列值不为空,避免ListViewItem构造参数为null Dim idValue = If(dr(columnNames(0)) Is DBNull.Value, nullPlaceholder, dr(columnNames(0)).ToString) Dim item As New ListViewItem(idValue) For j As Integer = 1 To repo.getColumnCount - 1 Dim cellValue = If(dr(columnNames(j)) Is DBNull.Value, nullPlaceholder, dr(columnNames(j)).ToString) item.SubItems.Add(cellValue) Next lstOrderHistory.Items.Add(item) Loop lstOrderHistory.View = View.Details Else MessageBox.Show("No data available or failed to retrieve data") End If
3. 排查users表的特殊问题
- 检查
tableName参数是否正确:确认传入的表名是users(注意MySQL在区分大小写的系统中表名大小写敏感) - 验证权限:当前数据库用户是否拥有
users表的SELECT权限 - 核对列信息:确认
columnNames数组包含users表的所有列,且getColumnCount返回值与实际列数一致
内容的提问来源于stack exchange,提问作者I Forgot My Name
相关产品推荐
相关产品推荐

