Search code examples
c#.netloopswindows-phoneunhandled-exception

Why does my code that adds controls in a loop fail?


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?


Solution

  • 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);
        }
    }