简体   繁体   中英

Check list Box in C#

I have written program below with checkbox. which works fine. but i want to write it in one checklistbox but don't know how to check 1st checklistbox is checked or 2nd.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
                MessageBox.Show("CheckBox1 is checked");
            if (checkBox2.Checked)
                MessageBox.Show("CheckBox2 is checked");
        }
    }
}

Edit:it is a windows form application.

Try This:

foreach (var item in checkedListBox1.CheckedItems)
{
    /* iterate over all checked items from the checkedlistbox */
    MessageBox.Show(item.ToString());
}

EDIT: if you want to perform some operations based on the selected item Try This:

foreach (int item in checkedListBox1.CheckedIndices)
{
    switch (item)
    {
        case 0:/*first item selected here do something*/
            MessageBox.Show("1st item selected");
            break;

        case 1:/*first item selected here do something*/
            MessageBox.Show("2nd item selected");
            break;

        case 2:/*first item selected here do something*/
            MessageBox.Show("3rd item selected");
            break;
    }
}

Explanation:

From MSDN: CheckedListBox.CheckedIndices Property

Collection of checked indexes in this CheckedListBox.

The collection of checked indexes is a subset of the indexes into the collection of all items in the CheckedListBox control

SelectedIndices returns you the selectedindex values from the Checkedlistbox . for example if there are 10 items in checkedlistbox and if you select item 1,item5 and item7 then it returns their respective index values(index always start with 0).

so it returns 0,4,6.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM