Search code examples
c#wpflinq-to-sqlcheckboxgrid

How would I add Checbox dynamically into a Grid in WPF application


I would like to add some Checkbox in a Grid control dynamically when the window is loaded in my C# Desktop application. How many times the checkbox will appear depends on the number of entries in a table. Here, I used LINQ To SQL class. The Grid control is defined in XAML.

...
<Grid Name="grid1">
   <!-- here i would like to show all check box -->
</Grid>
...

Code behind file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
// class declaration ...
...
private void course_Loaded(object sender, RoutedEventArgs e)
    {
        List<Course> courses = ldc.Courses.ToList();
        foreach (var c in courses)
        {
            CheckBox cb = new CheckBox();
            cb.Name=c.CourseID.ToString();
            cb.Content = c.CourseID.ToString();
            //grid1.Controls.Add(cb); does not work. what to do here?
        }
    }

This code is not working. Any suggession? Thankyou.


Solution

  • I suggest adding these CheckBoxes to a StackPanel and then add the StackPanel to the grid:

    StackPanel innerStack;
    
    private void course_Loaded(object sender, RoutedEventArgs e)
    {
        innerStack= new StackPanel 
        {
            Orientation=Orientation.Vertical
        };
        List<Course> courses = ldc.Courses.ToList();
    
        foreach (var c in courses)
        {
            CheckBox cb = new CheckBox();
            cb.Name = c.CourseID.ToString();
            cb.Content = c.CourseID.ToString();
            innerStack.Children.Add(cb);
        }
        Grid.SetColumn(innerStack,  /*Set the column of your stackPanel, default is 0*/);
        Grid.SetRow(innerStack,  /*Set the row of your stackPanel, default is 0*/);
        Grid.SetColumnSpan(innerStack,  /*Set the columnSpan of your stackPanel, default is 1*/);
        Grid.SetRowSpan(innerStack,  /*Set the rowSpan of your stackPanel, default is 1*/);
    
        Grid.Children.Add(innerStack);
    }
    

    If you do not want this structure, you should add some RowDefinition to your grid and use Grid.SetRow(cb, int) method to put ComboBoxes over each other.