Warm tip: This article is reproduced from stackoverflow.com, please click
c# sql

Select data from Datagridview using checkedlistbox

发布于 2020-03-28 23:13:26

I've got a datagridview in my form and also a checkedlistbox. I've written some code so that I can filter the datagridview with whatever is checked in the checkedlistbox. Although, it will only filter one at a time whereas I want to be able to filter any data which is checked. Is there a way around this?

Code:

if (checkedListBox1.CheckedItems.Count != 0)
{
    string s = "";
    int x;
    for (x = 0; x <= checkedListBox1.CheckedItems.Count - 1; x++)
    {
        s = "'" + checkedListBox1.CheckedItems[x].ToString() + "',";
    }

    s = s.Substring(0, s.Length - 1);
    toolStripDropDownButton7.Text = s;

    con.Open();
    string query = "select * from Leads where Status in (" + s + ")";
    SqlCommand cmd = new SqlCommand(query, con);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    sda.Fill(dt);
    dataGridView4.DataSource = dt;
    con.Close();
}
Questioner
Joe Carter
Viewed
18
VDN 2020-01-31 17:38

Looks like you have an error in your for loop: "s" contains only last checked item from checkListBox. Try to change it like this:

s += "'" + checkedListBox1.CheckedItems[x].ToString() + "',";