2014-02-19 28 views
0

我剛剛進入使用數據庫。我創建了一個似乎可以工作的類。我在這裏有一個我用教程創建的函數。它是DataAccess.class文件的一部分。我感到困惑的是如何;從一個類調用函數

A)包括在我的 和 B幹活,形式DataAccess.class文件)的一個按鈕

這裏調用插入函數的代碼是提前

Public Shared Function InsertNewRecord(ByVal item1 As String, ByVal item2 As String, ByVal item3 As String) As Boolean 
'Create the objects we need to insert a new record 
Dim cnInsert As New OleDbConnection(GetConnectionString("YourConnName")) 
Dim cmdInsert As New OleDbCommand 
Dim query As String = "INSERT INTO YourTable(column1,column2,column3)  VALUES(@item1,@item2,@item3)" 
Dim iSqlStatus As Integer 

'Clear any parameters 
cmdInsert.Parameters.Clear() 
Try 
    'Set the OleDbCommand Object Properties 
    With cmdInsert 
     'Tell it what to execute 
     .CommandText = query 
     'Tell it its a text query 
     .CommandType = CommandType.Text 
     'Now add the parameters to our query 
     'NOTE: Replace @value1.... with your parameter names in your query 
     'and add all your parameters in this fashion 
     .Parameters.AddWithValue("@value1", item1) 
     .Parameters.AddWithValue("@value2", item2) 
     .Parameters.AddWithValue("@value3", item3) 
     'Set the connection of the object 
     .Connection = cnInsert 
    End With 

    'Now take care of the connection 
    HandleConnection(cnInsert) 

    'Set the iSqlStatus to the ExecuteNonQuery 
    'status of the insert (0 = failed, 1 = success) 
    iSqlStatus = cmdInsert.ExecuteNonQuery 

    'Now check the status 
    If Not iSqlStatus = 0 Then 
     'DO your failed messaging here 
     Return False 
    Else 
    'Do your success work here 
     Return True 
    End If 
Catch ex As Exception 
    MsgBox(ex.Message, "Error") 
Finally 
    'Now close the connection 
    HandleConnection(cnInsert) 
End Try 
End Function 

謝謝

回答

-2

您是否嘗試通過點擊按鈕「調用InsertNewRecord」?

+0

是的,它說它沒有聲明 – Rabastan

+0

在SO規則中禁止這種真正意見的答案 – ElektroStudios

1
Yes, It says its not declared 

要使用用其他類中的公共共享功能,你可以做這些事情之一:

  1. 只需導入你的類到您正在嘗試調用該函數並再次嘗試班。

    Imports NameOfYourClass 
    
  2. 如果您沒有導入了中學班級到您的主類,那麼你需要的功能名稱前指定您的輔助類的名稱。

    Public class Form1 
    
    Private Sub Test() 
    
        ' Call a function from other Class. 
        NameOfYourClass.InsertNewRecord 
    
    End Sub 
    
    End Class 
    

這是否解決了您的問題?