Pass control as parameter

Asked

Viewed 555 times

0

Hello, I’m doing a reduction of some lines of code in Vb.net, one of them is a search function that creates an Autocomplete from a database, the code that does this is as follows:

 Private Sub pesquisaNome(ByVal txtNome As TextBox)
    reconect()
    txtNome.AutoCompleteMode = AutoCompleteMode.Suggest
    txtNome.AutoCompleteSource = AutoCompleteSource.CustomSource

    strsql = "SELECT * FROM motorista WHERE motorista_nome LIKE '%" & txtNome.Text & "%'"
    Dim objCommand As New MySqlCommand(strsql, conn)
    dr_usuario = objCommand.ExecuteReader()

    While (dr_usuario.Read())
        txtNome.AutoCompleteCustomSource.Add(dr_usuario.Item("motorista_nome"))
    End While
End Sub

I have three different search fields, one by Name, one by RG and one by CPF, and each of them has a code exactly like this, changing only 3 arguments, the Where clause (motorista_name, motorista_rg etc...), the text of the Textbox control (txtNome.text "driver name", txtRG.text "rg number" etc. and the txtName, txtRG control etc..., I decided to create a function and pass these values by parameters:

Private Sub search(clausula As String, campo As String, controle As Object)
    strsql = "SELECT * FROM motorista WHERE" & clausula & " LIKE '%" & campo & "%'"
    Dim objCommand As New MySqlCommand(strsql, conn)
    dr_usuario = objCommand.ExecuteReader()
    While (dr_usuario.Read())
        controle.AutoCompleteCustomSource.Add(dr_usuario.Item(campo))
    End While
End Sub

and the passage would be something like this:

search("motorista_nome",txtnome,txtnome.text)

and my doubt is precisely how to pass the control by parameter, or if there is another way to join these searches in a single code??

Thank you in advance!

  • Why reconect() is in the first function and in the second not?

  • This function is only to renew connection, Conn.close(), Conn.open() whenever some function will interact with the database it is necessary to check the connection.

1 answer

2


Try that one there:

Private Sub search(clausula As String, campo As String, ByRef controle As System.Windows.Forms.TextBox)
   strsql = "SELECT * FROM motorista WHERE " & clausula & " LIKE '%" & campo & "%'"
   Dim objCommand As New MySqlCommand(strsql, conn)
   dr_usuario = objCommand.ExecuteReader()
   While (dr_usuario.Read())
      controle.AutoCompleteCustomSource.Add(dr_usuario.Item(clausula ))
   End While
End Sub
  • 1

    THANK YOU SO MUCH! just that!! thank you very much indeed!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.