Binku Binku - 5 months ago 19
MySQL Question

Send Multiple Values to Mysql Query

Here Is the Story :

I have a checked list which has items from my database need to write a query to get only the selected items details which will then populate the gridviwe

object[] items = checkedListBox1.CheckedItems.OfType<object>().ToArray();

foreach (var item in items)
{



string connectionString = "server=127.0.0.1;uid=root;pwd=admin;database=per_update;";
string query = "select * from tblcenters where centerName in('" + item + "')";
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, conn))
{
DataTable ds = new DataTable();
adapter.Fill(ds);


dataGridView1.DataSource = ds;
}


}
}

i wrote this code it only gets me the details about the last item that I select. but I need the details to all the items i select

please don't worry about not using parameters in query since this is a sample

Answer

Try to build the string you have to use in the WHERE IN statement like this:

var whereValues = "''";

foreach (var item in items) {
    whereValues += ", '" + item + "'";
}

string query = "select * from tblcenters where centerName in(" + whereValues + ")";