0

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.

Fvcundo
  • 95
  • 2
  • 3
  • 11

1 Answers1

1

Reference For More Help , Click Here

you should write this casting

cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
 Int32 count = (Int32) cmd.ExecuteScalar();
MONTS_MIND_Hacker
  • 1,727
  • 2
  • 9
  • 9
  • @Fvcundo , you haveused CInt that's also for type conversation , but try (Int32) also....otherwise may be there is Database Connection Problem or may be Query Problem – MONTS_MIND_Hacker Feb 19 '15 at 03:48
  • 1
    Whoa. I never thought of using COUNT. Well, it worked man. Thanks a lot. – Fvcundo Feb 19 '15 at 03:49
  • @Fvcundo , First of all check that your query is working excute on sql server first...Then if working then check your connection string......otherwise your code is OK to run........ – MONTS_MIND_Hacker Feb 19 '15 at 03:50