views:

385

answers:

2

I'm trying to populate a listbox with a series checkbox entries, however once running the code below the listbox has blank entries in it, which are selectable, i.e. a blue bar appears. However neither the text or checkbox appears.

for (int num = 1; num <= 10; num++)
{
   CheckBox checkBox = new CheckBox();
   checkBox.Text = "sheet" + num.ToString();
   checkBox.Name = "checkbox" + num.ToString();

   thelistbox.Items.Add(checkBox);
}
+8  A: 

The best way to handle this is to create a list of data -- in your case, a list of numbers (or a list of strings (sheet1, sheet2, etc). You can then assign that list of numbers to thelistbox.ItemsSource. Inside the XAML of your listbox, set the ItemTemplate to include a CheckBox and bind the number to the text of the checkbox.

Brian Genisio
Good idea, I catch your drift.
wonea
+1  A: 

Try changing

checkBox.Text = "sheet" + num.ToString();

to

checkBox.Content = "sheet" + num.ToString();

With that change, I was able to use your example successfully.

Ben Collier
Strange there's doesn't seem to be a definition for .Content
wonea
Ah, I think that might help explain it! The winforms checkbox has a text property (but no content), whereas the WPF checkbox has a content property (but no text). It would appear that you are using a winforms checkbox.
Ben Collier