从类中调用函数

时间:2014-02-19 01:13:13

标签: vb.net winforms ms-access ado.net ado

我刚开始使用数据库。我创建了一个似乎有效的类。我在这里有一个我用教程创建的函数。它是DataAccess.class文件的一部分。我感到困惑的是如何;

A)以我正在处理的形式包含DataAccess.class文件 和 B)使用按钮调用插入函数

这是代码

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 个答案:

答案 0 :(得分: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
    
  3. 这是否解决了您的问题?

答案 1 :(得分:-2)

您是否在点击按钮时尝试“调用InsertNewRecord”?