H.Kathiri
H.Kathiri

Reputation: 35

Like with substring

What I'm trying to do in the below code is to let users add '%' first if they want to search for cat starts with a char.

if (textBox1.text.StartsWith("%"))
{
    sql = "Select cat from items where cat like '%" +textBox1.text.Substring(1)+"'";
    command = new SqlCommand(sql, cnn);
    dataReader = command.ExecuteReader();
    while (dataReader.Read())
    {
        listBox2.Items.Add(dataReader.GetString(0));
    }
    dataReader.Close();
    command.Dispose();

But nothing is shown in the list box.

Upvotes: 2

Views: 135

Answers (1)

Johan Gov
Johan Gov

Reputation: 1352

Do you get any results if you take the generated sql and run it directly towards the database?

If you want to search for items starting with a specific char the syntax is like 'x%' if x is your character. You currently have the percentage sign and the characters switched and are asking the database for all cats ending with your specified character. To search for cats starting with a specific character you want:

sql = "Select cat from items where cat like '" +textBox1.text.Substring(1)+"%'";

Upvotes: 1

Related Questions