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?
5条答案
按热度按时间jei2mxaa1#
Maybe instead of
You meant to use the value of a textbox? Like:
vjhs03f72#
The workaround was using the guide of this user from here . What was done by the author was that of overriding the default combobox setting in winforms. I just found a way to tie it into my code and got it up and running. I will outline how it works
And this is the Custom comboBox implementation:
6ovsh4lw3#
This sample works to filter the combo items based on the hint text but has an issue when the combobox overwrites the hint with selected text. It re-populates the combobox each time you type another letter.
mv1qrgav4#
If you are using framework 4.0 or upper, then you can try only adding the following line after populate the datasource, that is to say, after filcari() in the constructor.
and remove the where clause in your query.
cgh8pdjw5#