IndexOutOfRangeException未处理VBNET

时间:2015-02-19 11:43:35

标签: vb.net

我有一个从数据库中检索CurrentYear year_now和NextYear year_next的表单。它给了我错误'IndexOutOfRangeException未处理'bcoz我认为没有要检索的行。而我想做的是,即使表中没有数据,我仍然可以加载表单并给我一个空值来显示。我尝试了所有我知道的工作,但我无法解决问题。无论如何都要重新编码。

 Sub LoadSchoolYear()
    Dim conn1 As New MySqlConnection("server=localhost; userid=root; password=root; database=uecp_cens")
    Dim dAdapter1 As New MySqlDataAdapter("SELECT year_now, year_next FROM uecp_cens.tblschoolyear", conn1)
    Dim dTable1 As New DataSet
    Try
        dAdapter1.Fill(dTable1, "uecp_cens")
        lblYearNow.Text = dTable1.Tables("uecp_cens").Rows(0).Item(0).ToString
        lblYearNext.Text = dTable1.Tables("uecp_cens").Rows(0).Item(1).ToString
    Catch ex As MySqlException
        MsgBox(ex.Message)
    Finally
        conn1.Dispose()
    End Try
End Sub

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

如果您提到的表中没有行,则会出现该错误。请检查Rows.Count

Dim yearNow As String = Nothing
Dim yearNext As String = Nothing
If dTable1.Tables("uecp_cens").Rows.Count > 0 Then 
    yearNow = dTable1.Tables("uecp_cens").Rows(0).Item(0).ToString()
    yearNext = dTable1.Tables("uecp_cens").Rows(0).Item(1).ToString()
End If
lblYearNow.Text = yearNow
lblYearNext.Text = yearNext 

如果数据库中的字段为NULL,则为DBNull.Value,如果您使用Rows(0).Item(0).ToString(),则会出现异常。然后使用DataRow.IsNull进行检查:

If dTable1.Tables("uecp_cens").Rows.Count > 0 Then 
    Dim row = dTable1.Tables("uecp_cens").Rows(0)
    yearNow = If(row.IsNull(0), Nothing,  row.Item(0).ToString())
    yearNext = If(row.IsNull(1), Nothing,  row.Item(1).ToString())
End If
相关问题