2013-10-06 28 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

哦對不起。我很着急,所以沒有完全閱讀你的代碼。會嘗試一下,然後告訴你。 –