How to insert a check box inside a list box in C#?

2019-02-25 14:26发布

问题:

I want a code to insert a checkbox inside a listbox in c sharp. on selecting the checkbox all the items in listbox must get selected.

回答1:

You can use a CheckListBox to display a list with a check box next to each item.

But to make a single checkbox that selects everything in a list, it must be outside the list box (above or below or beside it). Then you can use code like:

public void SelectAllCheckBox_CheckedChanged(object s, EventArgs e) 
{
    foreach (var item in ListBox1.Items) 
    {
        item.Selected = SelectAllCheckBox.Checked;
    }
}

There is no control that has a single check box inside a list: eg this is what you mean:

+----------------------------------------+
| [x] Select All                         |
| Item one                               |
| Item two                               |
| Item three                             |
| Item four                              |
| Item five                              |
+----------------------------------------+

Instead you must use two controls: a checkbox and a separate list box:

[x] Select All                         

+----------------------------------------+
| Item one                               |
| Item two                               |
| Item three                             |
| Item four                              |
| Item five                              |
+----------------------------------------+


回答2:

Maybe you could extend the mentioned CheckedListBox, and handle a few Events so that only the first CheckBox is visible (maybe some kind of formatting event would be good for that).

And don't forget to use the onCheckedChangeEvent, so that you (de-)select all elements on change of the checkbox-value.