开发者

C# Iterate Through CheckBoxList Insert Selected Items Into SQL Columns

开发者 https://www.devze.com 2023-03-07 06:29 出处:网络
I have a CheckBoxList that displays around 20 options.I would like to iterate through and take the selected items from the list and insert them into 5 different columns in a database.

I have a CheckBoxList that displays around 20 options. I would like to iterate through and take the selected items from the list and insert them into 5 different columns in a database.

I开发者_JAVA百科 disable the checkboxlist after 5 items are selected so I am good there. I just need to know how to iterate through and insert the selected items.

How would I get this accomplished? Thanks in advance!


you can get the checked checkboxes like this

var checkedCheckBoxes = this.Controls.OfType<CheckBox>()
                            .Where(c => c.Checked);

replace this with a container that has the checkboxes if it's not the outer most container such as a Form.

and then you can loop thru items in checkedCheckBoxes and formulate your insert statement.


Do you have list of checkboxes or CheckedListBox control?

As answers have been provided for first one already, take a look at CheckedIndices or CheckedItems properties of CheckedListBox control in case that's what you use.

Quick example:

// Cast<string>() should be replaced by whatever data type you use
var checkedItems = checkedListBox.CheckedItems.Cast<string>();
foreach (var item in checkedItems)
{
    Debug.WriteLine(item);
}


Try this:

CheckBoxList1.Items.Cast<CheckBox>()
                   .Where(s => s.Checked)
                   .Take(5);
0

精彩评论

暂无评论...
验证码 换一张
取 消