Reputation: 3416
Following is my code for adding CheckBoxes dynamically to a 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)));
}
The problem is that whenever I run this code, the checkboxes are added but not with the text. Like this:
I tried to debug it and then I found that CheckBox instance 'c' is getting Text but not showing it.
See here:
Please tell me what's wrong going on in this code?
UPDATE
Please note that I can't use it like this:
Invoke(new Action(()=>checkedListBox1.Controls.Add(c)));
because its better to use panel instead of CheckBoxList then. Also I want two values one shown as text and other hidden as value for each CheckBox in CheckBoxList
UPDATE 2
Code to get selected items:
List<string> SelInts = new List<string>();
foreach (ListBoxItem c in checkedListBox1.SelectedItems)
{
SelInts.Add(c.Tag.ToString());
}
Upvotes: 3
Views: 4821
Reputation: 1
hope this helps u can do only declare the listitem and set the name and value
ListItem item = new ListItem();
item.Text = "text on checkbox";
item.Value = "Value of checkbox";
item.Enabled = true;
// add to the current checkbox list that u using
CheckBoxList1.Items.Add(item);
Upvotes: 0
Reputation: 347
What worked for me was to do
Invoke(new Action(()=>checkedListBox1.Items.Add(c.Text, true)));
instead of
Invoke(new Action(()=>checkedListBox1.Items.Add(c, true)));
Hope this helps.
Upvotes: 1
Reputation: 63377
Try this:
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;
}
}
I doubt that somehow your CheckBox
can't be displayed as a string although it should show the System.Windows.Forms.CheckBox
instead of blanks.
Upvotes: 3