Search code examples
c#.netwinformscheckedlistbox

How to get value of checked item from CheckedListBox?


I have used a CheckedListBox over my WinForm in C#. I have bounded this control as shown below -

chlCompanies.DataSource = dsCompanies.Tables[0];
chlCompanies.DisplayMember = "CompanyName";
chlCompanies.ValueMember = "ID";

I can get the indices of checked items, but how can i get checked item text and value. Rather how can i enumerate through CheckedItems accessing Text and Value?

Thanks for sharing your time.


Solution

  • Cast it back to its original type, which will be a DataRowView if you're binding a table, and you can then get the Id and Text from the appropriate columns:

    foreach(object itemChecked in checkedListBox1.CheckedItems)
    {
         DataRowView castedItem = itemChecked as DataRowView;
         string comapnyName = castedItem["CompanyName"];
         int? id = castedItem["ID"];
    }