2016-06-21 63 views
0

這裏參數值從String到的Int32轉換的代碼:未能在嘗試將值添加到SQL數據庫

Private m_cn As New SqlConnection 
Private m_DA As SqlDataAdapter 
Private m_CB As SqlCommandBuilder 
Private m_DataTable As New DataTable 
Private m_intRowPosition As Integer = 0 


Private Sub InsertDatabaseItem_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
    m_cn.ConnectionString = "Data Source=TREVOR-PC\SQLSERVEREXPRESS;Initial Catalog=Milk Convience Products;Integrated Security=True" 

    m_cn.Open() 
    m_DA = New SqlDataAdapter("Select * From ProductIndex", m_cn) 
    m_CB = New SqlCommandBuilder(m_DA) 

    txtBarcode.Focus() 

End Sub 

Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click 
    Dim cmd As New SqlCommand(("INSERT INTO ProductIndex VALUES(" & 
           "@ID," & 
           "@Name," & 
           "@Price," & 
           "@Desc)" & 
           "@Barcode)"), m_cn) 

    cmd.Parameters.Add("@ID", SqlDbType.Int) 
    cmd.Parameters("@ID").Value = txtID.Text 
    cmd.Parameters.Add("@Name", SqlDbType.VarChar) 
    cmd.Parameters("@Name").Value = txtName.Text 
    cmd.Parameters.Add("@Price", SqlDbType.Money) 
    cmd.Parameters("@Price").Value = txtPrice.Text 
    cmd.Parameters.Add("@Desc", SqlDbType.VarChar) 
    cmd.Parameters("@Desc").Value = txtDesc.Text 
    cmd.Parameters.Add("@Barcode", SqlDbType.BigInt) 
    cmd.Parameters("@Barcode").Value = txtBarcode.Text 

    cmd.ExecuteNonQuery() 

    MsgBox("Success!", MsgBoxStyle.Information, "SUCCESS") 

    Me.Hide() 

    txtID.Clear() 
    txtName.Clear() 
    txtPrice.Clear() 
    txtDesc.Clear() 
    txtBarcode.Clear() 

    m_cn.Close() 
    m_cn.Dispose() 
End Sub 


Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click 
    Me.Hide() 
End Sub 

我點擊btnOK後進入一個新的數據庫項目,出現異常它說:無法將參數值從字符串轉換爲Int32。

我做了一些調試,發現發生後的「cmd.Parameters(」 @條形碼「)的錯誤。值= txtBarcode.Text」的代碼行

回答

1
cmd.Parameters.Add("@Barcode", SqlDbType.BigInt) 
cmd.Parameters("@Barcode").Value = txtBarcode.Text 

您正試圖施放txtBarcode .Text作爲大整數。這應該通過顯式轉換值來完成。您的測試用例很可能是空字符串或其他無法轉換的字符串值。

請注意重新讀取您的代碼,這可能也是Id和Price參數的問題。