Search code examples
vb.netdbnullexecutescalar

How to handle DBNull? VB.NET


I have form that has datagrid and some textbox controls. Basically, Im performing Add function. Whenever I add, it scans the maximum value and it will increment by one. I only designed for auto increment. My problem is, how can I increment when the ExecuteScalar gets a null value. Here's the sample codes

 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

Any help is appreciated.


Solution

  • Reference For More Help , Click Here

    you should write this casting

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