Conversion from type 'DBNull' to type 'String' is not valid.

abhit_kumar

Member
Joined
Aug 13, 2008
Messages
19
Programming Experience
Beginner
Hello Experts,

I have tried to display autoincrement number from database filed to TextBox at Form.

Database type of that field is Int.

The below code is work correct, but when the database is empty then its throw the error like:-

Conversion from type 'DBNull' to type 'String' is not valid.


VB.NET:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

       

        Try
            myConnection.Open()
            Dim strsql As String
            strsql = "SELECT MAX(DocEntry)+1 FROM InwardMaster"
            Dim com As New SqlCommand(strsql, myConnection)

            DocEntry.Text = com.ExecuteScalar

        Catch sqlex As SqlException
            MessageBox.Show(sqlex.Message)
        End Try



        myConnection.Close()


    End Sub

Please correct my code where its incorrect.



Regards,

AKM
 
Hello. Try the following. I have not really worked too much with SQL in VB, but it's worth a shot. :)

VB.NET:
Try
            myConnection.Open()
            Dim strsql As String
            strsql = "SELECT MAX(DocEntry)+1 FROM InwardMaster"
            Dim com As New SqlCommand(strsql, myConnection)

            DocEntry.Text = com.ExecuteScalar[B].ToString[/B]
                      'OR YOU COULD TRY:
            [B]DocEntry.Text = CTYPE(com.ExecuteScalar, String)[/B]

        Catch sqlex As SqlException
            MessageBox.Show(sqlex.Message)
        End Try
 
Last edited:
Back
Top