Share via


How to loop through a checkedlistbox and want to get value and text of checkedlistbox

Question

Thursday, January 24, 2013 9:27 AM

i am working in c# 2.0 win from project.i want to iterate in checklistbox collection and want to check that each item is checked or not. if checked then i want to store that item text and value too.

i wrote this code in this way but not working.

    for (int i = 0; i < lstcjkEmployee.Items.Count-1; i++)
    {
                    if (lstcjkEmployee.Items[i].selected)
                    {
                        string strVal = lstcjkEmployee.Items[i].Value;
                        
                    }
    }

please help me.

All replies (2)

Thursday, January 24, 2013 9:48 AM âś…Answered

any way i have sort it.

private void Form1_Load(object sender, EventArgs e)
        {
            List<Person> lst = new List<Person>();

            lst.Add(new Person(1,"Ram"));
            lst.Add(new Person(2, "Sam"));
            lst.Add(new Person(3, "Rom"));

            ((ListBox)this.checkedListBox1).DataSource = lst;
            ((ListBox)this.checkedListBox1).DisplayMember = "Name";
            ((ListBox)this.checkedListBox1).ValueMember = "ID";

        }

        private void button1_Click(object sender, EventArgs e)
        {
            bool chk = false;
            for (int i = 0; i < checkedListBox1.Items.Count; i++)
            {
                if (this.checkedListBox1.GetItemCheckState(i) == CheckState.Checked)
                {
                    chk = true;
                    //this.checkedListBox1.SelectedItem.ToString() 
                }
                else
                {
                    chk = false;
                }
                Person obj = (Person) checkedListBox1.Items[i];
                MessageBox.Show(obj.ID + "  " + obj.Name + "  Checked " + chk);
            }
        }
public class Person
    {
        public int ID { get; set; }
        public string Name { get; set; }

        public Person(int ID, string Name)
        {
            this.ID = ID;
            this.Name = Name;
        }
    }

http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/a5484060-4f3e-4d87-b2c7-401134ce71be


Friday, January 25, 2013 2:56 AM

Hi Mou_kolkata,

  Welcome to MSDN Forum Support.

  I am glad to hear that you have solved this problem by searching the existing threads which has mentioned your problem. Thank you for sharing its related solutions with us,Hope you come back when encountering other problems.

  Sincerely,

  Jason Wang

Jason Wang [MSFT]
MSDN Community Support | Feedback to us