Query search C# Oledb

Asked

Viewed 74 times

3

In the program I am working on, I have made a data search form, where the name entered will be searched in the database and will return next results

(Search screen)

The problem is that the query will only return some data if what is inserted in the textbox is identical to what is recorded in the database

My query:

private void populate(string name)
    {
        lvPesquisa.Items.Add(new ListViewItem(new[] { name }));
    }

private void pbSearch_Click(object sender, EventArgs e)
    {
        string strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
               + Application.StartupPath + @"\NOME DO BANCO.mdb";

        OleDbConnection dbConnection = new OleDbConnection(strConnection);

        OleDbCommand cmdQry = dbConnection.CreateCommand();

        Nome = txtNome.Text;

        try
        {
            dbConnection.Open();

            OleDbCommand cmd = new OleDbCommand("SELECT nomeCadastro FROM TABELA WHERE nomeCadastro=? ORDER BY nomeCadastro ASC", dbConnection);
            OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);

            adapter.SelectCommand.Parameters.AddWithValue("@nome", Nome);
            DataTable dt = new DataTable();
            adapter.SelectCommand = cmd;
            adapter.Fill(dt);
            //LOOP THROUGH DATATABLE
            foreach (DataRow row in dt.Rows)
            {
                populate(row[0].ToString());
            }


            //CLEAR DATATABLE
            dt.Rows.Clear();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            dbConnection.Close();
        }
    }

(Table and database name were removed - LISTVIEW is called lvPesquisa and there is only 1 column)

I need the query to return data similar to the one typed in the text box. Any ideas? Grateful.

  • Try to use the operator LIKE, the operator LIKE is used to search for a particular string within a textual value field. With it we can, for example, search the records whose NAME starts with a certain word, or contains a certain text. To perform this type of query, we can also use the character % to indicate a coringa, that is, any text that can appear in the field. For example: SELECT * FROM PESSOA WHERE Nome LIKE '%@nome%'

  • Unfortunately it didn’t work out. But thank you

1 answer

2


Try to put the like as suggested our friend Albert As follows:

OleDbCommand cmd = new OleDbCommand("SELECT nomeCadastro FROM TABELA WHERE 
                                    nomeCadastro like ? ORDER BY nomeCadastro ASC", dbConnection);
        OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);

        adapter.SelectCommand.Parameters.Add("@nome", OleDbType.VarChar).Value = "%" + Nome + "%";
  • It worked perfectly! Thank you very much.

Browser other questions tagged

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