2014-02-19 29 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 
    

这是否解决了您的问题?