1

I'm having trouble finding the right format for converting my txtID and txtCatID into integers since it's in numbers in the database access.

Code

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles btnSave.Click

    Dim sqlinsert As String

    sqlinsert = _
        "INSERT INTO Products (ProductID, Product, UnitPrice, CategoryName, CategoryID)" & _
        " VALUES (@ProductID, @Product, @UnitPrice, @CategoryName, @CategoryID)"
    Dim cmd As New OleDb.OleDbCommand(sqlinsert, con1)

    cmd.Parameters.Add(New OleDbParameter("@ProductID", (txtID.Text)))
    cmd.Parameters.Add(New OleDbParameter("@Product", txtProd.Text))
    cmd.Parameters.Add(New OleDbParameter("@UnitPrice", txtPrice.Text))
    cmd.Parameters.Add(New OleDbParameter("@CategoryName",txtCategory.Text))
    cmd.Parameters.Add(New OleDbParameter("@CategoryID", (txtCatID.Text)))

    con1.Open()
    cmd.ExecuteNonQuery()
    con1.Close()

    ClearTextBox(Me)
    RefreshDGV()
    Me.Close()
1

3 Answers 3

3

You can convert String to int by doing like this:

  1. For C#: int val = Int32.Parse("12");
  2. For VB.NET: Dim val as Integer = CInt("12")

Here you can find all Type Conversion Functions (Visual Basic).

Here you have How to: Convert a String to a Number (C# Programming Guide).

Sign up to request clarification or add additional context in comments.

Comments

1

You can convert string from a TextBox to an integer using:

Dim myInt as Integer = CInt(Textbox1.Text)

Otherwise, if you are asking how to ensure that an integer is appended into an SQL file or Access file using VB.NET, then that's a different question.

Comments

1

I solved it:

Dim productID As Integer

If (Integer.TryParse(txtID.Text, productID)) Then

    cmd.Parameters.Add(New OleDbParameter("@ProductID", productID))
Else
    Throw New ArgumentException("Entered ProductID is not a valid integer.")
End If


cmd.Parameters.Add(New OleDbParameter("@Product", txtProd.Text))

Dim price As Double
If (Double.TryParse(txtPrice.Text, price)) Then

    cmd.Parameters.Add(New OleDbParameter("@UnitPrice", txtPrice.Text))
Else
    Throw New ArgumentException("Invalid.")
End If

cmd.Parameters.Add(New OleDbParameter("@CategoryName", txtCategory.Text))

Dim id As Integer
If (Integer.TryParse(txtCatID.Text, id)) Then
    cmd.Parameters.Add(New OleDbParameter("@CategoryID", id))
Else
    Throw New ArgumentException("Entered Category ID is Invalid.")
End If

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.