Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

LIKE clause issue in c# but works in SQL Server Express

Ok so I was having this issue of my comboBox value not returning the results I wanted based on a project I was working on.

So the issue is this: I want to search by way of a substring in the comboBox. To clarify,I want a string from the comboBox to return the necessary value based on any part of the string I entered. Currently all it does is populate the comboBox with the items. What I want is after populating the comboBox it should return a string based on any character I type in. So let's say I have the word "stack123" when I type "123" or "k" or any substring, it will narrow the comboBox items and show the values based on the substring entered or just return the word "stack123"

string query = "SELECT * FROM dbo.Carimed WHERE Item_Description LIKE '%" + comboBox1.Text.Trim().Replace("'", "''") + "%'; "; 

And I don't know if this helps but this is the full thing:

using System;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace comboBoxTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            fillCari();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        void fillCari()//fill Cari-med dropdown with values
        {
            try
            {
                string connectionString = "Data Source=LPMSW09000012JD\SQLEXPRESS;Initial Catalog=Carimed_Inventory;Integrated Security=True";
                SqlConnection con2 = new SqlConnection(connectionString);
                con2.Open();
                string query = "SELECT * FROM dbo.Carimed WHERE Item_Description LIKE '%" + comboBox1.Text.Trim().Replace("'", "''") + "%'; "; 
                SqlCommand cmd2 = new SqlCommand(query, con2);

                SqlDataReader dr2 = cmd2.ExecuteReader();

                while (dr2.Read())
                {
                    string cari_des = dr2.GetString(dr2.GetOrdinal("Item_Description"));
                    comboBox1.Items.Add(cari_des);
                }

                con2.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}

What could be the problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Maybe instead of

'%" + comboBox1.Text.Trim().Replace("'", "''") + "%' 

You meant to use the value of a textbox? Like:

'%" + textBox1.Text.Trim().Replace("'", "''") + "%' 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...