【问题标题】:How to find selected items in checkbox list binded from database如何从数据库中查找复选框列表绑定中的选定项目
【发布时间】:2013-04-14 10:03:57
【问题描述】:

在复选框列表中查找选中的项目时遇到问题。实际上,复选框列表的列表项是从数据库加载的。但是通过使用下面的代码,我无法在列表中找到选中的项目,并且这些项目总是返回 false。下面是我的代码有人可以帮我吗?

 protected void GetCheckboxlist_Click(object sender, EventArgs e)
        {
            string s = string.Empty;
            for (int i = 0; i < CheckBoxList1.Items.Count; i++)
            {

            if (CheckBoxList1.Items[i].Selected)
            {

                // List the selected items
                s = s + CheckBoxList1.Items[i].Text + ",";

            }

        }
    }

【问题讨论】:

    标签: c# asp.net database binding checkboxlist


    【解决方案1】:

    您的代码在我看来不错,但请尝试改用 Linq

    IEnumerable<string> CheckedItems = CheckBoxList1.Items.Cast<ListItem>()
                                       .Where(i => i.Selected)
                                       .Select(i => i.Value);
    

    之后,您可以添加您的s 字符串这些值,例如;

    foreach(string i in CheckedItems)
            s += i + ",";
    

    别忘了添加System.Linq命名空间。

    【讨论】:

    • @user545359 很高兴听到它;)
    • 现在我可以将选中的项目作为数据库中每行的每个项目保存到数据库中。你能告诉我如何从数据库中检索数据并将其分配给复选框列表作为选中项。
    猜你喜欢
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多