I have SQL Server database for users, and now I want to make simple search algorithm for this table. My goal is to make algorithm that can combine search of multiple words, so I tried with this strategy: when search button is pressed, method first extracts individual words from search string and then inserts them as a parameters in SqlCommand CommandText.
It works for one word but it gets stuck when I type more than one word. Here is the code sample:
private void btnSearchUsers_Click(object sender, EventArgs e)
{
command = new SqlCommand();
adapter = new SqlDataAdapter();
dataset = new DataSet();
try
{
User.connection.Open();
command.CommandText = "SELECT * FROM tbl_Users WHERE userActive = 1";
if (!String.Empty.Equals(tboxInputUsers.Text))
{
command.CommandText += " AND";
string[] words = tboxInputUsers.Text.Split(' ');
string id = "id";
foreach (string word in words)
{
id += "a";
command.CommandText += String.Format(" userUsername LIKE @{0} OR userName LIKE @{0} OR userSurname LIKE @{0}", id);
command.Parameters.AddWithValue(String.Format("@{0}", id), word);
}
}
command.Connection = User.connection;
adapter.SelectCommand = command;
adapter.Fill(dataset);
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (ConnectionState.Open.Equals(User.connection.State)) Korisnik.connection.Close();
}
DataTable table = new DataTable();
table = dataset.Tables[0];
dgvUsers.DataSource = table;
dgvUsers.Columns[0].Visible = false;
}
When I go to debug mode and type in two words, command.Parameters shows it has 2 parameters, but it cracks nevertheless. Any insights what is wrong?
Thanks!
== EDIT ==
I get this type of
SqlException: Incorrect syntax near 'userUsername'