Newton Sheikh
Newton Sheikh

Reputation: 56

Select/Unselect all Rows in a grid

I have a DataGrid in wpf form. It has rows with checkboxes in it. I want to select/unselect all the rows with the header checkbox selected/unselected.

But I am getting this error: "Object reference not set to an instance of an object" on chk.IsChecked = false.

enter image description here

c# code:

private void myDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        CheckBox chk = (CheckBox)this.myDataGrid.Columns[0].GetCellContent(e.Row);
        chk.IsChecked = false;
        checkboxes.Add(chk);
    }

xaml code is:

<Window x:Class="WpfApplication1.Grid"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Grid" Height="300" Width="300">
<Grid>
    <DataGrid x:Name="myDataGrid"
              VerticalAlignment="Top"
              Grid.Column="0"
              AutoGenerateColumns="False"
              LoadingRow="myDataGrid_LoadingRow"
              Loaded="myDataGrid_Loaded">
        <DataGrid.Columns>
            <DataGridTemplateColumn Width="80">
                <DataGridTemplateColumn.Header>
                    <CheckBox HorizontalAlignment="Center"
                              Click="chk_Click"
                              VerticalAlignment="Center"
                              Name="chckAll">
                    </CheckBox>
                </DataGridTemplateColumn.Header>

                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <CheckBox x:Name="chk"
                                  HorizontalAlignment="Center"
                                  HorizontalContentAlignment="Center"></CheckBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

            <DataGridTextColumn Header="First Name"
                                Width="100"
                                Binding="{Binding FirstName}"></DataGridTextColumn>
            <DataGridTextColumn Header="Last Name"
                                Width="100"
                                Binding="{Binding LastName}"></DataGridTextColumn>
        </DataGrid.Columns> 
    </DataGrid>
</Grid>

Thanks in advance.

Upvotes: 0

Views: 1299

Answers (1)

Sonhja
Sonhja

Reputation: 8448

You can do what they say on this link.

For you should be something like this:

DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(dataGrid.SelectedIndex);
CheckBox chk = (CheckBox)this.myDataGrid.Columns[0].GetCellContent(e.Row);

I guess, not trying right now.

Upvotes: 1

Related Questions