Search for text in all columns and rows of a database table

This code should find the word entered in textBox6 in all rows and columns of the table. The compiler does not issue errors, but the code itself does not search. Most likely, it's the wrong syntax or the wrong sql query.

private void button5_Click(object sender, EventArgs e)
{
   if (textBox6.Text != "")
   {
       sqlcon.Open();
       SqlCommand query = new SqlCommand("SELECT * FROM  Info WHERE (SurName LIKE '%" + textBox6.Text + "%' OR Name LIKE '%" + textBox6.Text + "%' OR MiddleName LIKE '%" + textBox6.Text + "%' OR OfficePhone  LIKE '%" + textBox6.Text + "%' OR MobilePhone LIKE '%" + textBox6.Text + "%' OR IDDolj LIKE '%" + textBox6.Text + "%')", sqlcon);
       query.ExecuteNonQuery();
       sqlcon.Close();
   }
   else
   {
       MessageBox.Show("Error");
   }
}

Upvotes: 0

Views: 196

Answers (1)

Fuzzy
Fuzzy

Reputation: 496

As mentioned in the comments. You probably want to do something with the result of the query, so instead of using ExeucteNonQuery() you could use ExecuteReader().

I would also definitely use SqlParameters to prevent SQLInjection.

private void button5_Click(object sender, EventArgs e)
{
    if (!String.IsNullOrEmpty(textBox6.Text))
    {
        sqlcon.Open();
        SqlCommand query = new SqlCommand("SELECT * FROM Info WHERE (SurName LIKE @searchText OR Name LIKE @searchText OR MiddleName LIKE @searchText OR OfficePhone  LIKE @searchText OR MobilePhone LIKE @searchText OR IDDolj LIKE @searchText)", sqlcon);
        SqlParameter searchTextParam = new SqlParameter("searchText", "%" + textBox6.Text + "%");
        query.Parameters.Add(searchTextParam);
        DataReader results = query.ExecuteReader();
        // Do something with the results here.
        sqlcon.Close();
    }
    else
    {
        MessageBox.Show("Error");
    }
}

Upvotes: 1

Related Questions