c# - 将复选框动态添加到不显示文本的 CheckBoxList

标签 c# .net winforms user-interface checkbox

以下是我将复选框动态添加到 CheckBoxList 的代码:

foreach (WCore.CategoryFields cat in Global.getCategories())
{
        CheckBox c = new CheckBox();
        c.Text = cat.CategoryId;
        c.Tag = cat.CategoryName;
        if (ints != null)
        {
            if (ints.Contains(c.Tag))
               Invoke(new Action(()=>checkedListBox1.Items.Add(c, true)));
            else
               Invoke(new Action(()=>checkedListBox1.Items.Add(c, false)));
        }
        else
            Invoke(new Action(()=>checkedListBox1.Items.Add(c, false)));
}

问题是每当我运行这段代码时,都会添加复选框,但不会添加文本。像这样: enter image description here

我尝试对其进行调试,然后我发现 CheckBox 实例“c”正在获取文本但未显示它。

看这里: enter image description here

请告诉我这段代码出了什么问题?

更新

请注意,我不能这样使用它:

Invoke(new Action(()=>checkedListBox1.Controls.Add(c)));

因为那时最好使用面板而不是 CheckBoxList。 我还想要两个值,一个显示为文本,另一个隐藏为 CheckBoxList 中每个 CheckBox 的值

更新 2

获取选中项的代码:

List<string> SelInts = new List<string>();
foreach (ListBoxItem c in checkedListBox1.SelectedItems)
{
        SelInts.Add(c.Tag.ToString());
}

最佳答案

试试这个:

foreach (WCore.CategoryFields cat in Global.getCategories()){
    ListBoxItem c = new ListBoxItem;
    c.Text = cat.CategoryId;
    c.Tag = cat.CategoryName;
    if (ints != null)
    {
        if (ints.Contains(c.Tag))
           Invoke(new Action(()=>checkedListBox1.Items.Add(c, true)));
        else
           Invoke(new Action(()=>checkedListBox1.Items.Add(c, false)));
    }
    else
        Invoke(new Action(()=>checkedListBox1.Items.Add(c, false)));
}
//Add this class somewhere in your form class or beside it
public class ListBoxItem {
   public string Text {get;set;}
   public object Tag {get;set;}
   public override string ToString(){
      return Text;
   }
}

我怀疑你的 CheckBox 不能以某种方式显示为字符串,尽管它应该显示 System.Windows.Forms.CheckBox 而不是空白。

关于c# - 将复选框动态添加到不显示文本的 CheckBoxList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19214084/

相关文章:

c# - 消除随机重复?

c# - 我的 http 模块中未触发 BeginRequest 事件

javascript - 防止用户篡改 View 的增量代码

winforms - 如何编辑外部 web.config 文件?

.net - 获取ListBox显示高度

c# - 使用存储在 session 中的 Guid 过滤 Linq

c# - 对象的 map 集合

asp.net - 我可以使用 owin 和 oauth 提供商的 asp.net 成员(member)资格吗?

c# - 如何压缩目录然后返回生成的字节数组,而无需在磁盘上物理创建 zip 文件?

C# winforms如何在不同的事件处理程序中访问同一对象