0
public MainPage()
{
    InitializeComponent();
    CheckBox c = new CheckBox();
    for (int i = 0; i < 2; i++)
    {
       c.Content = " Value ";
       lbox.Items.Add(c);
    }
}

lbox is an empty listbox in the UI and the above code throws an unhandled exception which is caught by code in App.xaml.cs. The code works fine if I remove for loop. What's wrong with this code?

Tilak
  • 30,108
  • 19
  • 83
  • 131
Indish
  • 739
  • 1
  • 7
  • 12

5 Answers5

5

You are initializing CheckBox outside the loop once, and adding it twice. Move it inside the for loop.

    for (int i = 0; i < 2; i++)
    {
        CheckBox c = new CheckBox();
        c.Content = " Value " ;
        lbox.Items.Add(c);
    }
Tilak
  • 30,108
  • 19
  • 83
  • 131
4

Create a new instance of checkbox in the loop

public MainPage()
{
    InitializeComponent();

    for (int i = 0; i < 2; i++)
    {
        CheckBox c = new CheckBox();
        c.Content = " Value " ;
        lbox.Items.Add(c);
    }
}
CR41G14
  • 5,464
  • 5
  • 43
  • 64
3

try putting the check box inside the loop

public MainPage()
{
    InitializeComponent();

    for (int i = 0; i < 2; i++)
    {
        CheckBox c = new CheckBox();
        c.Content = " Value " ;
        lbox.Items.Add(c);
    }
}
iJade
  • 23,144
  • 56
  • 154
  • 243
1

Bellow code it's OK:

in Form1.Designer.cs you must define:

partial class From1
{   
    private.System.Windows.Forms.ListBox lbos;
    private.System.Windows.Forms.CheckBox c;
}

and in Form1.cs you must write:

public MainPage()
{
    InitializeComponent();

    for (int i = 0; i < 2; i++)
    {
        this.c.Text = " Value " ;
        this.lbox.Items.Add(c);
    }
}
0
public MainPage()
{
    InitializeComponent();
    for (int i = 0; i < 2; i++)
    {
        lbox.Items.Add(new CheckBox{Content =" Value "});
    }
}
burning_LEGION
  • 13,246
  • 8
  • 40
  • 52