c# – CheckListBox for collection property in PropertyGrid

Question:

I have a small class from UITypeEditor that I need to have a drop-down list with checkboxes in the PropertyGrid for the collection property. For example, I create a category of products (fruits, vegetables) in the grocery list and there is a list of all products in which I need to select those that belong to this category. Those. I add a new category "Fruit" to the empty grocery list, and for this category I select from the global list of products those that belong to it: "Apples", "Pears", "Bananas". Next, I want to create another category, for example "Vegetables" and again select some vegetables from the global list. The problem is that after creating the last category, all other categories receive the same set of products as the last one. here is the code:

public class CheckedListBoxUiTypeEditor : UITypeEditor
{
    private readonly CheckedListBox _checklisbox1 = new CheckedListBox();

    private IWindowsFormsEditorService _es;

    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
        return UITypeEditorEditStyle.DropDown;
    }

    public override bool IsDropDownResizable => true;

    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
        if (provider != null)
        {
            _es = provider.GetService(typeof (IWindowsFormsEditorService)) as IWindowsFormsEditorService;
        }

        if (_es != null)
        {
            LoadValues(value);
            _es.DropDownControl(_checklisbox1);
        }

        _result.Clear();

        foreach (string str in _checklisbox1.CheckedItems)
        {
            _result.Add(str);
        }
        return _result;
    }

    private readonly List<string> _defaultList = FormLas.ListAll;

    private readonly List<string> _result = new List<string>(); 

    private void LoadValues(object value)
    {
        Hashtable table = new Hashtable();
        foreach (string str in _defaultList)
        {
            table.Add(str, false);
        }
        _checklisbox1.Items.Clear();
        foreach (DictionaryEntry dic in table)
        {
            _checklisbox1.Items.Add(dic.Key, (bool) dic.Value);
        }

        if (((List<string>) value).Count > 0)
        {
            foreach (string str in (List<string>)value)
            {
                for (int i = 0; i < _checklisbox1.Items.Count; i++)
                {
                    if (str == _checklisbox1.Items[i])
                    {
                        _checklisbox1.SetItemChecked(i, true);
                    }
                }
            }
        }
    }
}

Answer:

Found an error, the problem was in the global variables (_defaultList, _result), the initialization of these variables must be placed in the body of the methods. Do the same for the _checklisbox1 object.

Scroll to Top
AllEscort