Nasay Nasay - 13 days ago 7
C# Question

CheckListBox property collection in PropertyGrid

I have a class of UITypeEditor, so that in PropertyGrid property collection was CheckListBox. For example, I create a category of products (fruits, vegetables) in a grocery list and a list of all the products which I need to select the ones that fall into this category. Those. I add an empty grocery list new category "Fruits", and for this category is selected from a global list of those products which it includes: "Apples", "Pear", "Bananas". Next I want to create another category, such as "vegetables" and then choose from a global list of some vegetables. The problem is that after the establishment of the latter category, and all other categories receive the same set of products that last. here's 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 error, the problem was global variables (_defaultList, _result), initialization of these variables must be placed in the body techniques. The same should be done to _checklisbox1 object.