如何将 checkBoxList 项目设置为只读或将其删除?

How to make a checkBoxList item readonly or remove it?

我正在开发一个 windows form 应用程序,它在 checkboxList 中显示我在 datagridview 中的所有列。首先,我设置 checked SQL 中的所有项目 that can be null。我想 delete 所有其他 that are not checked 或让它们 readonly。我试过 cast 它作为复选框,但它不起作用。我尝试从复选框列表中删除一个项目,但出现以下错误 Items collection cannot be modified when the DataSource property is set.

有什么想法或提示吗?

foreach (DataGridViewColumn column in ((MainSoftwareForm)mainSoftware).dataGridViewImportParts.Columns)
        {
            var columns = ((MainSoftwareForm)mainSoftware).dataGridViewImportParts.Columns.Cast<DataGridViewColumn>()
            .Select(x => new { x.Name, x.HeaderText }).ToList();
            checkedListBoxIPColumns.DataSource = columns;
            checkedListBoxIPColumns.ValueMember = "Name";
            checkedListBoxIPColumns.DisplayMember = "HeaderText";

             //Set initial check state based on columns visibility
            for (int i = 0; i < checkedListBoxIPColumns.Items.Count; i++)
            {
                if(mOS_PackOSDataSet.PARTLIST.Columns[i].AllowDBNull==true)
                {
                    dynamic item = checkedListBoxIPColumns.Items[i];

                    checkedListBoxIPColumns.SetItemChecked(i, true);                       
                }    
                else
                {

                }
            }

            checkedListBoxIPColumns.ItemCheck += (obj, args) =>
            {
                dynamic item = checkedListBoxIPColumns.Items[args.Index];              
                var visible = args.NewValue == CheckState.Checked ? true : false;
                ((MainSoftwareForm)mainSoftware).dataGridViewImportParts.Columns[(string)item.Name].Visible = visible;                 
            };             
        }

如果您要投反对票,我很乐意解释原因:)

我找到了我的问题的解决方案。如果在 SQL 中不允许它们为 null,我将它们一直设置为未选中。

checkedListBoxPartList.ItemCheck += (obj, args) =>
            {
                if (mOS_PackOSDataSet.PARTLIST.Columns[args.Index].AllowDBNull == true)
                {
                    dynamic testOne = checkedListBoxPartList.Items[args.Index];
                    var test = args.NewValue == CheckState.Checked ? true : false;
                    ((MainSoftwareForm)mainSoftware).dataGridViewPartLists.Columns[(string)testOne.Name].Visible = test;
                }
                else
                {
                    dynamic item = checkedListBoxPartList.Items[args.Index];
                    if (args.CurrentValue == CheckState.Unchecked) args.NewValue = CheckState.Unchecked;
                    var visibleIndeterminate = args.NewValue == CheckState.Unchecked ? false : false;
                    ((MainSoftwareForm)mainSoftware).dataGridViewPartLists.Columns[(string)item.Name].Visible = visibleIndeterminate;
                }


            };