Search code examples
c#winformscheckedlistbox

How to loop all data in checkedlistbox?


How to loop all data in checkedlistbox in 'PROPER' way and print it on console or pop up on messagebox one by one?

I populated my clbPackages this way

// clbPackages is a checkedlistbox
SqlCommand scPackages = new SqlCommand("SELECT XXX FROM XXX", sqlConnection);
SqlDataReader readerPackages;
readerPackages = scPackages.ExecuteReader();
DataTable dtPackages = new DataTable();
dtPackages.Columns.Add("PACKAGE_GROUP_ID", typeof(string));
dtPackages.Columns.Add("PACKAGE_GROUP_NAME", typeof(string));
dtPackages.Load(readerPackages);

this.clbPackages.DataSource = dtPackages;
this.clbPackages.ValueMember = "PACKAGE_GROUP_ID";
this.clbPackages.DisplayMember = "PACKAGE_GROUP_NAME";

Now I have to loop that checkedlistbox because I am trying to check some in, my best try is this code below

foreach (var item in clbPackages.Items)
{
    MessageBox.Show(item.ToString());               
} 

It only return xxx.xxx.DataRowView, and if I try to loop again the item it will show error "foreach statement cannot operate on variables of type 'object' because 'object' "


answered by Bjorn

other way to deal

foreach (object item in clbPackages.Items)
{     
    DataRowView castedItem = item as DataRowView;
    string groupId= castedItem["PACKAGE_GROUP_ID"].ToString();
    MessageBox.Show(groupId);
}

Solution

  • Sounds like the objects in the Items-collection is of type DataRowView. So if you convert each item to a DataRowView and get the value from that object you should be fine:

    foreach (DataRowView item in clbPackages.Items)
    {
        MessageBox.Show(item["PACKAGE_GROUP_NAME"].ToString());               
    }