InvalidCastException Etc.

icookiprog

New member
Joined
Apr 3, 2007
Messages
2
Programming Experience
3-5
I've been working on this for at least a day now and could not figure what exactly is wrong with my code. I kept getting ""Invalid CastException was unhandled error - Conversion from string "" to type integer is not valid" when trying to add new client and "NullReferenceException was unhandled - Object variable or With block variable not set."" when I try to edit a client. And it is always with clientno. On the backend clientno is an identity field (int 4).

This is the code that I use on the btnSave to send updates to the server
VB.NET:
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        If ValidData() Then
            If Me.NewClient Then
                Me.SetClientFields(Client)
                Client.clientno = ClientDB.InsertClient(Client)
                Me.Close()
            Else
                Dim NewClient As New Client()
                Me.SetClientFields(NewClient)
                NewClient.clientno = lblClientNo.Text
                If ClientDB.UpdateClient(NewClient, Client) Then
                    Client = NewClient
                    Me.Close()
                End If
            End If
        End If
    End Sub

This the ClientDB Class which has the code for adding new and updating client
VB.NET:
Imports System.Data.SqlClient
Public Class ClientDB
    Public Shared Function InsertClient(ByVal Client As Client) As Integer
        Using conPSCIS As SqlConnection = New SqlConnection(connectionString)
            Dim sInsertClient As String
            sInsertClient = "INSERT INTO tblClients " _
            & "(firstname, lastname, address1, address2, city, state, zip) " _
            & "VALUES (@firstname, @lastname, @address1, @address2, @city, @state, @zip) "
            Dim commandInsertClient As New SqlCommand(sInsertClient, conPSCIS)
            With commandInsertClient.Parameters
                .AddWithValue("@firstname", Client.firstname)
                .AddWithValue("@lastname", Client.lastname)
                .AddWithValue("@address1", Client.address1)
                .AddWithValue("@address2", Client.address2)
                .AddWithValue("@city", Client.city)
                .AddWithValue("@state", Client.state)
                .AddWithValue("@zip", Client.state)
            End With
            conPSCIS.Open()
            commandInsertClient.ExecuteNonQuery()
            commandInsertClient.CommandText = "SELECT @@IDENTITY"
            Client.clientno = commandInsertClient.ExecuteScalar
            Return Client.clientno
        End Using
    End Function

    Public Shared Function UpdateClient(ByVal NewClient, ByVal OldClient) As Boolean
        Dim bUpdate As Boolean = True
        Using conPSCIS As SqlConnection = New SqlConnection(connectionString)

            Dim sUpdateClient As String
            sUpdateClient = "UPDATE tblClients " _
            & "SET firstname = @firstname, " _
            & "lastname = @lastname, " _
            & "address1 = @address1, " _
            & "address2 = @address2, " _
            & "city = @city, " _
            & "state = @state, " _
            & "zip = @zip " _
            & "WHERE clientno = @clientno " _
            & "AND firstname = @oldfirstname " _
            & "AND lastname = @oldlastname " _
            & "AND address1 = @oldaddress1 " _
            & "AND address2 = @oldaddress2 " _
            & "AND city = @oldcity " _
            & "AND state = @oldstate " _
            & "AND zip = @oldzip"
            Dim commandUpdateClient As New SqlCommand(sUpdateClient, conPSCIS)
            With commandUpdateClient.Parameters
                .AddWithValue("@clientno", OldClient.clientno.ToString)
                .AddWithValue("@firstname", NewClient.firstname)
                .AddWithValue("@lastname", NewClient.lastname)
                .AddWithValue("@address1", NewClient.address1)
                .AddWithValue("@address2", NewClient.address2)
                .AddWithValue("@city", NewClient.city)
                .AddWithValue("@state", NewClient.state)
                .AddWithValue("@zip", NewClient.zip)
                .AddWithValue("@oldfirstname", OldClient.firstname)
                .AddWithValue("@oldlastname", OldClient.lastname)
                .AddWithValue("@oldaddress1", OldClient.address1)
                .AddWithValue("@oldaddress2", OldClient.address2)
                .AddWithValue("@oldcity", OldClient.city)
                .AddWithValue("@oldstate", OldClient.state)
                .AddWithValue("@oldzip", OldClient.zip)
            End With
            conPSCIS.Open()
            If commandUpdateClient.ExecuteNonQuery() = 0 Then
                MessageBox.Show("Another user has modified or deleted this client. " _
                & "Please try again.", "Concurrency error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                bUpdate = False
            End If
            Return bUpdate
        End Using

    End Function
End Class

And here is my Client Class
VB.NET:
Public Class Client
    Public clientno As Integer
    Public firstname As String
    Public lastname As String
    Public address1 As String
    Public address2 As String
    Public city As String
    Public state As String
    Public zip As String
End Class

Please help.
 
Last edited:
Could you maybe point out where exactly the exceptions are thrown so we don't have to trawl all that code?

This line is an issue:
VB.NET:
NewClient.clientno = lblClientNo.Text
The Text property of a control returns a String, while your clientno field is type Integer. Now, a string can contain any combination of characters, so does it make sense that you should be able to simply assign it to a variable that requires a number? Even if a string contains only digits it is still not a number; it's a string of digits. Your code is forcing an implicit conversion from a String to an Integer. If that string doesn't contain a valid representation of a number then an exception is thrown. The first error message is telling you exactly that: an empty string cannot be converted to an integer.

You should be validating your string to ensure that it contains a valid value and, if it does, you should be explicitly converting it yourself:
VB.NET:
Integer.TryParse(lblClientNo.Text, NewClient.clientno)
If you are expecting that string to contain a valid value and it doesn't then there's an issue elsewhere in your code. You need to determine where that value was supposed to be set and work out why it isn't.

As for the second error, I have no idea where it's being thrown and I'm not inclined to try to work it out. Please point out exactly where it occurs.
 
I think this is doing pretty much the same as the above code, but I shal post it anyway, incase it comes in useful, possibly in other circumstances aswell:

VB.NET:
dim x as integer
Try
x = Cint(textbox1.text)
Catch ex as invalidcastexception
End Try
or
VB.NET:
x = CType(textbox1.text, integer)

And as said above, don't post too much code, i didn't bother reading it, hence i used x and textbox 1, at the very least highlight the line that generates the error
 
I think this is doing pretty much the same as the above code, but I shal post it anyway, incase it comes in useful, possibly in other circumstances aswell:

VB.NET:
dim x as integer
Try
x = Cint(textbox1.text)
Catch ex as invalidcastexception
End Try
or
VB.NET:
x = CType(textbox1.text, integer)

And as said above, don't post too much code, i didn't bother reading it, hence i used x and textbox 1, at the very least highlight the line that generates the error
You should never let an exception be thrown if you don't have to. Throwing exceptions is expensive and makes for inefficient code. Prevention is better than cure.
 
Back
Top