2012-12-06 26 views
0

我有一個需要一個整數的字段的訪問數據庫。我傳入從Excel電子表格中檢索的一些數據,如果從單元格中檢索到字符串,則調用函數的Try/Catch將遇到FormatException。我試圖弄清楚的是,如果有可能(並且總是)拋出一個自定義錯誤消息,該消息將顯示包含無效數據的單元地址。以下是我所擁有的一些示例代碼。捕獲訪問數據庫錯誤(FormatException)並返回自定義消息?

Public Class Main 
Private cellAddress As String 
Private Sub btn_Import(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImport.Click 
    Dim openFileDialog As New OpenFileDialog() 
    openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) 
    openFileDialog.Filter = "Excel Files (*.xls)|*.xlsx|All files (*.*)|*.*" 
    openFileDialog.RestoreDirectory = True 
    If openFileDialog.ShowDialog() <> Windows.Forms.DialogResult.OK Then 
     Return 
    End If 
    Try 
     ImportWorksheet(New FileInfo(openFileDialog.FileName)) 
    Catch ex As FormatException 
     MessageBox.Show("The data contained within cell " & cellAddress & " is invalid.", "Error") 
    End Try 
End Sub 

Private Sub ImportWorksheet(ByVal excelFile As FileInfo) 
    Dim cnn As New OleDbConnection(My.Settings.cnn) 
    Dim cmd As OleDbCommand = GetCommand("UpdateSite") 
    Dim worksheet1 As ExcelWorksheet = package.Workbook.Worksheets(1) 
    Using package As New ExcelPackage(excelFile) 
     Using cmd.Connection 
      cmd.Connection.Open() 
      cmd.Parameters.Add("@MyData", OleDbType.Integer).Value = GetCellContents(worksheet1, "K8") 
      cmd.ExecuteNonQuery() 
     End Using 
End Sub 

Private Function GetCellContents(ByVal worksheet As ExcelWorksheet, ByVal address As String) As Object 
    If worksheet.Cells(address).Value Is Nothing Then 
     Return DBNull.Value 
    Else 
     cellAddress = address 
     Return worksheet.Cells(address).Value 
    End If 
End Function 
End Class 

不要以爲我在這裏缺少什麼,我有點複製和粘貼和修改代碼以縮短和不放棄任何不必要的信息。一旦代碼碰到ExecuteNonQuery()方法,錯誤就會冒出來,並說出我寫過的任何東西。我想在這種情況發生時通過單元格地址,如果可能的話,他們知道在哪裏尋找。

我能想到這樣做的唯一方法是添加一個類級變量,並在每次獲取該值時將其設置爲當前單元格。唯一的問題是,因爲它只觸發ExecuteNonQuery(),並且我有多個參數,如果第一個添加的參數是無效的,但下一個參數不是,那麼每次都將單元設置爲最後一個參數,錯誤的結果。有沒有辦法從數據庫中獲取某種類型的消息,它會告訴我具體哪個參數沒有正確轉換?

回答

0

沒關係,我剛剛就這麼做了......它可以工作,但如果你們可以給我更好的東西,請做。

cmd.Parameters.Add("@MyData", OleDbType.Integer).Value = GetCellContents(worksheet2, "K8", "Int32") 

Private Function GetCellContents(ByVal worksheet As ExcelWorksheet, ByVal address As String, Optional ByVal type As String = Nothing) As Object 
    If worksheet.Cells(address).Value Is Nothing Then 
     Return DBNull.Value 
    Else 
     cellAddress = address 
     Select Case type 
      Case Is = "String" 
       Return Convert.ToString(worksheet.Cells(address).Value) 
      Case Is = "Int32" 
       Return Convert.ToInt32(worksheet.Cells(address).Value) 
      Case Is = "DateTime" 
       Return Convert.ToDateTime(worksheet.Cells(address).Value) 
      Case Else 
       Return worksheet.Cells(address).Value 
     End Select 
    End If 
End Function