Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have one checklistbox and datagridview, i want to select multiple items from checkedlistbox and the corresponding data need to fetch from database and display in datagridview, the below code is working when I select one item from checklistbox but when I select more then one item below code is not working.

What I have tried:

C#
string str = "";
            if (Checkedlistbox1.CheckedItems.Count > 0)
            {
                for (int i = 0; i < Checkedlistbox1.CheckedItems.Count; i++)
                {
                        str += Checkedlistbox1.CheckedItems[i].ToString();
                }
             
                string strassign = "Select * from xyz where assigngrp in ('" + str + "')";
                try
                {
                    sda = new SqlDataAdapter(strassign, con);
                    ds = new DataSet();
                    SqlCommandBuilder scb = new SqlCommandBuilder(sda);
                    sda.Fill(ds, "xyz");
                    bsource.DataSource = ds.Tables["xyz"];
                    gridview.DataSource = bsource;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
Posted
Updated 23-Oct-16 11:38am

1 solution

Try replacing
C#
string str = "";
            if (Checkedlistbox1.CheckedItems.Count > 0)
            {
                for (int i = 0; i < Checkedlistbox1.CheckedItems.Count; i++)
                {
                        str += Checkedlistbox1.CheckedItems[i].ToString();
                }

By
C#
List<ListItem> selected = CheckBoxList1.Items.Cast<ListItem>()
.Where(li => li.Selected)
.ToList();

string str = selected.Select(p => p.Value).ToArray().Aggregate((current, next) => current + ", " + next);
 
Share this answer
 
Comments
Member 12673779 24-Oct-16 8:32am    
Is your code separating checkeditems by comma, if yes then we can write it in
str += Checkedlistbox1.CheckedItems[i].ToString() + ",";

But it won't work because my items are stored in different rows in table..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900