2013-10-06 32 views
2

以下是我对动态添加的CheckBox到CheckBoxList的代码:动态添加的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

请告诉我什么是错在这段代码怎么回事?

UPDATE

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

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

因为它能够更好地使用面板,而不是CheckBoxList的然后。 此外,我想两个值一个显示为文本和其他隐藏的价值为每个复选框中的CheckBoxList

更新2

代码获取所选项目:

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

我想你的意思是你想让'checked items'不是'selected items'? –

+0

雅谢谢,改变那工作:) –

回答

2

试试这个:

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不能显示为st尽管它应该显示System.Windows.Forms.CheckBox而不是空白。

+0

但VS显示此错误'无法找到类型或命名空间名'ListBoxItem'(你是否缺少using指令或程序集引用?)'。我想你是在告诉我WPF的答案。我正在开发这个应用程序在纯WinForms –

+0

@AishwaryaShiva不,我有一个名为'ListBoxItem'类,你应该将它添加到你的表单类中或它旁边。 –

+0

哦对不起。我很着急,所以没有完全阅读你的代码。会尝试一下,然后告诉你。 –