Search code examples
c#.netwinformscheckedlistboxchecklistbox

How to get Selected Items back back into the checkedListBox


I have checkedListBox called CLB_CONTROLLER that is loaded to the page to display names instead of ID: This information is stored in dbo.CHIPSET

public void loadCategory()
{
    CLB_CONTROLLER.DataSource = catg.getCategories();
    CLB_CONTROLLER.DisplayMember = "CHIPSET";
    CLB_CONTROLLER.ValueMember = "CHIPSET_ID";
}

Then I would insert data into the DB as string. This information is stored in dbo.MYDB

//LOOP THROUGH CONTROLLER CHECKED ITEMS TO INSERT ALL SELECTED
string chip = "";
for (int i = 0; i < CLB_CONTROLLER.CheckedItems.Count; i++)
{
    if (chip == "")
    {
        chip = CLB_CONTROLLER.GetItemText(CLB_CONTROLLER.CheckedItems[i]);
    }
    else
    {
        chip += ", " + CLB_CONTROLLER.GetItemText(CLB_CONTROLLER.CheckedItems[i]);
    }
}

So far so good… Now I want to create Update feature… When user selects cell from the DataGrid , I want to auto populate all textboxes, CheckBoxes etc. on the page. So I am trying to figure out how can I do that with CLB_CONTROLLER mentioned above. The Update is looking inside dbo.MYDB and the column 2 CHIPSET which is now a string (inserted with code above). I have this code below, but when I click on DataGrid, nothing happens inside the CLB_CONTROLLER

//CHECK IF CONTROLLER CONTAINES CONTENT, THEN SELLECT APPROPRIATE CHECK BOX
string con = DGV_AOC.CurrentRow.Cells[2].Value.ToString();
string[] convalues = con.Split(',');
for (int i = 0; i < convalues.Length; i++)
{
    convalues[i] = convalues[i].Trim();
}

for (int i = 0; i < CLB_CONTROLLER.Items.Count; i++)
{
    CLB_CONTROLLER.SetItemChecked(i, false);//First uncheck the old value!
    for (int x = 0; x < convalues.Length; x++)
    {
        if (CLB_CONTROLLER.Items[i].ToString() == convalues[x].ToString())
        {
            //Check only if they match! 
            CLB_CONTROLLER.SetItemChecked(i, true);
        }
    }
}

Any help would be greatly appreciated.


Solution

  • Let's say you have filled the CheckedListBox with a,b,c,d,e,f for example as item texts.

    Then you can set checked items based on a comma separated list this way:

    var itemsToSelect = "a,c,d";
    var items = itemsToSelect.Split(',');
    for (var i = 0; i < checkedListBox1.Items.Count; i++)
    {
        var b = items.Contains(checkedListBox1.GetItemText(checkedListBox1.Items[i]));
        checkedListBox1.SetItemChecked(i, b);
    }
    

    Also you can get checked items in a comma-separated string this way:

    var selectedItems = string.Join(",",
        checkedListBox1.CheckedItems.Cast<object>()
            .Select(x => checkedListBox1.GetItemText(x)));