如何处理DBNull? VB.NET

How to handle DBNull? VB.NET

我的表单包含数据网格和一些文本框控件。 基本上,我正在执行添加功能。每当我添加时,它都会扫描最大值并将递增 1。我只为自动递增而设计。我的问题是,当 ExecuteScalar 获得空值时,我该如何递增。 这是示例代码

 Public Sub IncrementID()
    conn = New MySqlConnection
    conn.ConnectionString = "server=localhost; userid=root; password=root; database=uecp_cens"

    Try
        conn.Open()
        Dim insert_coupon_query As String = ("SELECT MAX(faculty_ID) from uecp_cens.tblfacultyinfo")
        Dim cmd_query As New MySqlCommand(insert_coupon_query, conn)
        Dim cmd_result As Integer = CInt(cmd_query.ExecuteScalar()) 'THIS IS WHERE THE ERROR OCCURS, IT GIVES ME 'InvalidCastException was unhandled' Conversion from type 'DBNull' to type 'Integer' is not valid.
        txtFacultyNo.Text = cmd_result + 1
    Catch ex As MySqlException
        MessageBox.Show(ex.Message)
    Finally
        conn.Dispose()
    End Try
End Sub

感谢任何帮助。

Reference For More Help , Click Here

你应该写这个选角

cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
 Int32 count = (Int32) cmd.ExecuteScalar();