Home > Enterprise >  Dynamically add a column in WPF DataGrid
Dynamically add a column in WPF DataGrid

Time:09-21

I am working on an MVVM WPF DataGrid application. I have a DataGrid and a multiselect CheckBox dropdown menu above it. Whenever I select an option in the menu, I want to add a column in the DataGrid. Is there any way to do that?

enter image description here

CodePudding user response:

I have recently faced something similar in a C# uwp application. Here's what worked for me.


Firstly, I created a list to keep track of all checked checkboxes:

private List<CheckBox> checkedCheckboxes = new List<CheckBox>();

Then, I created the checkboxes and linked them to the same events like so (You probably have code for this part already):

foreach (foo blah in random)
        {
            var checkbox = new CheckBox(); //creating new checkbox
            checkbox.Content = blah.name; //setting content
            checkbox.Name = $"chk_{blah.name}"; //naming it
            checkbox.Tag = "blah"; //adding the tag

            checkbox.Checked  = CheckBox_Checked; //adding the checked event
            checkbox.Unchecked  = CheckBox_Unchecked; //adding the unchecked event

            ClassCheckboxes.Add(checkbox);
        }

For the "CheckBox_Checked" event I did the following:

private void CheckBox_Checked(object sender, RoutedEventArgs e)
    {
        checkedCheckboxes.Add((CheckBox)sender);
        //Here you can put some code to update your datagrid
    }

And for the "CheckBox_Unchecked" event I did the following:

private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
    {
        checkedCheckboxes.Remove((CheckBox)sender);
        //Here you can put some code to update your datagrid
    }

To add a new column to your datagrid, you can refer to this answer. There are a few nice strategies there that may work for you. Here's the highest voted one for your convenience:

DataGridTextColumn textColumn = new DataGridTextColumn(); 
textColumn.Header = "First Name"; 
textColumn.Binding = new Binding("FirstName"); 
dataGrid.Columns.Add(textColumn);

Sorry if I've done something wrong here, this is my first time posting an answer so go easy on me :)

  • Related