从checklistbox中选择多个项目并在datagridview中显示 [英] Select multiple items from checklistbox and show in datagridview

查看:128
本文介绍了从checklistbox中选择多个项目并在datagridview中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个checklistbox和datagridview,我想从checkedlistbox中选择多个项目,相应的数据需要从数据库中获取并显示在datagridview中,当我从checklistbox中选择一个项目但是当我选择更多时,下面的代码正常工作代码下面的一项不起作用。



我尝试了什么:



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:

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);
                }
            }

推荐答案

尝试更换

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



通过


By

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);


这篇关于从checklistbox中选择多个项目并在datagridview中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆