c# – Adding checkbox to datagrid lines

Question:

I have a WPF application, in which there is a window with a datagrid with several lines, having only records. In this window there is also a button and I need that the user, when clicking on the button, a checkbox appears in each line of the datagrid .

After the user has finished the checked list, he will click again on the button that will call a function, going through the datagrid lines and checking which ones are checked to do an action only on the checked records.

Answer:

You can add a column with Template of a checkbox in each line instead of just the name, for this the property of your object that will be added to the Datagrid must be a boolean.

<DataGrid AutoGenerateColumns="False" Name="dtgUsuarios">
    <DataGrid.Columns>

        <DataGridTemplateColumn Header="Habilitado">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding UsuarioHabilitado}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

         //Outras Colunas...
         //<DataGridTextColumn...            
         //<DataGridTextColumn...

    </DataGrid.Columns>
</DataGrid>

Add users to Datagrid:

Usuario user = new Usuario();

dtgUsuarios.Items.Add(user);

And finally, with the click of the button, update the checkbox values:

private void btAtualizar_Click(object sender, RoutedEventArgs e)
{
    foreach (var item in dtgUsuarios.Items)
    {
        bool novoValorCheckbox = item.UsuarioHabilitado;
    }
}
Scroll to Top