简体   繁体   English

如何处理DBNull? VB.NET

[英]How to handle DBNull? VB.NET

I have form that has datagrid and some textbox controls. 我有具有datagrid和一些文本框控件的窗体。 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. 我的问题是,当ExecuteScalar获得空值时,如何递增。 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. 任何帮助表示赞赏。

Reference For More Help , Click Here 参考以获得更多帮助,请单击此处

you should write this casting 你应该写这个演员表

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM