Public Sub auto_Suggest(ByVal member As String, ByVal table As String, ByVal txt As Object)
Try
dta = New DataTable
'open the connection
conn.Open()
'holds the data in the database
With cmda
.Connection = conn
.CommandText = "select " & member & " from " & table
End With
'''''''''''''''fill data in the table
daa.SelectCommand = cmda
daa.Fill(dta)
''function of autocomplete
Dim r As DataRow
txt.AutoCompleteCustomSource.Clear()
For Each r In dta.Rows
txt.AutoCompleteCustomSource.Add(r.Item(0).ToString)
Next
''''''''''''''''''''''''
Catch ex As Exception
MsgBox(ex.Message)
End Try
''''close the connection
conn.Close()
daa.Dispose()
End Sub
Private Sub Stock_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
'call a public sub
'the job_id is the field of a table , the employees is the name of a table and a textbox is an object
auto_Suggest("ItemName", "stock", TxtItemName)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
答案 0 :(得分:0)
首先,采用“使用它并失去它”的方法并利用使用块来自动处理连接,命令和读取器是很好的。请参阅下面的示例。
其次,请在Try语句后的第一行设置断点,然后在调试器中逐步执行源代码。如果达到异常,请检查ex变量,并可能检查ex.InnerException(如果有)。
最后,此处的示例使用SQLConnection和SQLCommand(SQL Server)。只需换掉你用于MySQL的任何库,你应该好好去。
Public Sub auto_Suggest(connectionString As String, member As String, table As String, txt As TextBox)
Try
txt.AutoCompleteCustomSource.Clear()
Using cn = New SqlConnection(connectionString)
cn.Open()
Using cmd = New SqlCommand("SELECT " & member & " FROM " & table, cn)
Using dr = cmd.ExecuteReader()
While dr.Read
txt.AutoCompleteCustomSource.Add(dr(member).ToString)
End While
End Using
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub