Search code examples
c#sqlloopscheckedlistbox

Populating and deleting items from a database table by looping through checkedlistbox


What I am trying to do is populate a second checkedlistbox based on the selected items in the first checkedlistbox, and remove the items from the database when the parent is unchecked in the first box. I am able to populate the second box by looping through only the checked items, however, I need to include the unchecked items as well if I am to delete them from the table. Here is the code I have at the moment:

        for (int i = 0; i < ckbObjectives.Items.Count; i++)
        {
            objectiveTableAdapter.ClearBeforeFill = false;

            if (ckbObjectives.GetItemChecked(i))
            {
                this.objectiveTableAdapter.FillByParentObjective((CWSToolkitDataSet.ObjectiveDataTable)cWSToolkitDataSet.Tables["ChildObjectives"], Convert.ToInt32(((DataRowView)ckbObjectives.Items[i])[ckbObjectives.ValueMember].ToString()));
            }
            else
            {
                this.objectiveTableAdapter.Delete((CWSToolkitDataSet.ObjectiveDataTable)cWSToolkitDataSet.Tables["ChildObjectives"], Convert.ToInt32(((DataRowView)ckbObjectives.Items[i])[ckbObjectives.ValueMember].ToString()));
            }
        }

        cblSubObjectives.DataSource = cWSToolkitDataSet.Tables["ChildObjectives"];
        cblSubObjectives.DisplayMember = "Title";
        cblSubObjectives.ValueMember = "ObjectiveID";

I am not getting any errors, however the second checkedlistbox isn't getting populated. Any help would be greatly appreciated. Thank you!


Solution

  • Assuming you're checking the right things, this should be working.

    Can you double check which CheckedListBox you're looping through, and ensure you're getting the right responses:

    for (int i = 0; i < ckbObjectives.Items.Count; i++)
    {
        MessageBox.Show(String.Format("{0}: {1}", 
                        ckbObjectives.GetItemText(ckbObjectives.Items[i]),
                        ckbObjectives.GetItemCheckState(i).ToString())); 
    }
    

    I'm still not sure if you're on WinForms/WebForms/WPF etc, but replace the MessageBox.Show above with whatever is best to output. This will at least assure you you're looking at the right, current, data.