DataGrid.Columns[i].GetCellContent(Item) returns null (C#)

رضا جافری 1,291 Reputation points
2022-03-21T13:57:06.647+00:00

First and foremost, I apologize for my grammatical errors; my first language is Persian (Iran).
I use the following method to calculate the total price and it works fine at first, but when I change the DataGrid.ItemsSource, line 27 returns a null error.
Note: EnableRowVirtualization must be set to false.
XAML:

    <DataGrid x:Name="BookDataGrid" ContextMenu="{StaticResource DataGridContextMenu}" HeadersVisibility="Column" EnableRowVirtualization="False" AutoGenerateColumns="False" ItemsSource="{Binding}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="486" Height="386" Margin="0">  
        <DataGrid.Columns>  
            <DataGridTextColumn x:Name="BookName" Binding="{Binding BookName}" Width="SizeToHeader"/>  
            <DataGridTextColumn x:Name="Publisher" Binding="{Binding Publisher}" Width="SizeToHeader"/>  
            <DataGridTextColumn x:Name="Category" Binding="{Binding Category}" Width="SizeToHeader"/>  
            <DataGridTextColumn x:Name="BookCode" Binding="{Binding BookCode}" Width="SizeToHeader"/>  
            <DataGridTextColumn x:Name="Inventory" Binding="{Binding Inventory}" Width="SizeToHeader"/>  
            <DataGridTextColumn x:Name="DateTaken" Binding="{Binding DateTaken}" Width="SizeToHeader"/>  
            <DataGridTextColumn x:Name="RecipientName" Binding="{Binding RecipientName}" Width="SizeToHeader"/>  
            <DataGridTextColumn x:Name="ReturnDate" Binding="{Binding ReturnDate}" Width="SizeToHeader"/>  
            <DataGridTextColumn x:Name="ReleaseDate" Binding="{Binding ReleaseDate}" Width="SizeToHeader"/>  
            <DataGridTextColumn x:Name="Language" Binding="{Binding BookLanguage}" Width="SizeToHeader"/>  
            <DataGridTextColumn x:Name="Length" Binding="{Binding Length}" Width="SizeToHeader"/>  
            <DataGridTextColumn x:Name="Form" Binding="{Binding Form}" Width="SizeToHeader"/>  
            <DataGridTextColumn x:Name="Translator" Binding="{Binding Translator}" Width="SizeToHeader"/>  
            <DataGridTextColumn x:Name="Narrator" Binding="{Binding Narrator}"/>  
            <DataGridTextColumn x:Name="ISBN" Binding="{Binding ISBN}"/>  
            <DataGridTextColumn x:Name="Location" Binding="{Binding Location}"/>  
            <DataGridTextColumn x:Name="Price" Binding="{Binding Price}"/>  
            <DataGridTemplateColumn x:Name="BookImage" Width="SizeToHeader">  
                <DataGridTemplateColumn.CellTemplate>  
                    <DataTemplate>  
                        <Image x:Name="BookImg" Source="{Binding BookImage}"/>  
                    </DataTemplate>  
                </DataGridTemplateColumn.CellTemplate>  
            </DataGridTemplateColumn>  
        </DataGrid.Columns>  
    </DataGrid>  

C#:

    public string GetDigit(string Text)  
    {  
        string Digit = null;  
        switch (Text)  
        {  
            case "":  
                break;  
            default:  
                for (byte i = 0; i < Text.Length && i <= 255; i++)  
                {  
                    switch (char.IsDigit(Text[i]))  
                    {  
                        case true:  
                            Digit += Text[i];  
                            break;  
                    }  
                }  
                break;  
        }  
        return Digit;  
    }  
    public void TotalPrice()  
    {  
        ulong Total = 0;  
        for (int i = 0; i < BookDataGrid.Items.Count - 1; i++)  
        {  
            Total += (ulong.Parse(GetDigit((BookDataGrid.Columns[16].GetCellContent(BookDataGrid.Items[i]) as TextBlock).Text)));  
        }  
        TotalPrice_TextBox.Text = ulong.Parse(Total.ToString().Replace(",", "")).ToString("n0");  
    }  

I use the following method to remove item from DataGrid.ItemsSource and it works fine:
Output:
185180-output.gif

    private void DataGridDeleteMenu_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)  
    {  
        List<object> DefaultRow = new List<object>();  
        for (int i = 0; i < BookDataGrid.Items.Count - 1; i++)  
        {  
            DefaultRow.Add(BookDataGrid.Items[i]);  
        }  
        for (int i = 0; i < BookDataGrid.SelectedItems.Count; i++)  
        {  
            DefaultRow.Remove(BookDataGrid.SelectedItems[i]);  
        }  
        BookDataGrid.ItemsSource = DefaultRow;  
        //Retrying to use the TotalPrice method returns a null error  
        TotalPrice();  
    }  

Note: In the Window Loaded event, the TotalPrice method works fine, but
Returns a null error when I try to use it again (after changing the DataGrid.ItemsSource).

XAML (definitions of Books_GroupBox & Members_GroupBox):

    <GroupBox x:Name="Books_GroupBox" Header="Books" Background="Transparent" Visibility="Hidden" HorizontalAlignment="Center" Width="500" Height="400" VerticalAlignment="Center">  
        <GroupBox.Style>  
            <Style TargetType="{x:Type GroupBox}">  
                <Setter Property="BorderBrush" Value="DarkGray"/>  
                <Setter Property="BorderThickness" Value="1"/>  
                <Setter Property="Template">  
                    <Setter.Value>  
                        <ControlTemplate TargetType="{x:Type GroupBox}">  
                            <Grid SnapsToDevicePixels="true">  
                                <Grid.ColumnDefinitions>  
                                    <ColumnDefinition Width="*"/>  
                                    <ColumnDefinition Width="*"/>  
                                    <ColumnDefinition Width="*"/>  
                                    <ColumnDefinition Width="*"/>  
                                </Grid.ColumnDefinitions>  
                                <Grid.RowDefinitions>  
                                    <RowDefinition Height="*"/>  
                                    <RowDefinition Height="*"/>  
                                    <RowDefinition Height="*"/>  
                                    <RowDefinition Height="*"/>  
                                </Grid.RowDefinitions>  
                                <Border BorderBrush="DarkGray"   
                                BorderThickness="1"  
                                CornerRadius="9"  
                                Grid.ColumnSpan="4"   
                                Grid.RowSpan="4">  
                                    <Border.OpacityMask>  
                                        <MultiBinding ConverterParameter="9">  
                                            <MultiBinding.Converter>  
                                                <BorderGapMaskConverter/>  
                                            </MultiBinding.Converter>  
                                            <Binding ElementName="Header" Path="ActualWidth"/>  
                                            <Binding Path="ActualWidth" RelativeSource="{RelativeSource Self}"/>  
                                            <Binding Path="ActualHeight" RelativeSource="{RelativeSource Self}"/>  
                                        </MultiBinding>  
                                    </Border.OpacityMask>  
                                </Border>  
                                <Border x:Name="Header" Grid.RowSpan="1" Grid.ColumnSpan="2"  Margin="9,-11.5,0,0" HorizontalAlignment="Left" VerticalAlignment="Top">  
                                    <ContentPresenter  ContentSource="Header"  
                                              RecognizesAccessKey="True"   
                                              SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>  
                                </Border>  
                                <ContentPresenter  Grid.ColumnSpan="2" Grid.Column="1" Grid.Row="1"   
                                          Margin="{TemplateBinding Padding}"  
                                          SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>  
                            </Grid>  
                        </ControlTemplate>  
                    </Setter.Value>  
                </Setter>  
            </Style>  
        </GroupBox.Style>  
        <ItemsControl Width="486" Height="386" Margin="-118,-93,-118,-193">  
            <Grid DataContext="{StaticResource BookTableViewSource}" Width="486" Height="386">  
                <DataGrid x:Name="BookDataGrid" ContextMenu="{StaticResource DataGridContextMenu}" HeadersVisibility="Column" EnableRowVirtualization="False" AutoGenerateColumns="False" ItemsSource="{Binding}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="486" Height="386" Margin="0">  
                    <DataGrid.Columns>  
                        <DataGridTextColumn x:Name="BookName" Binding="{Binding BookName}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="Publisher" Binding="{Binding Publisher}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="Category" Binding="{Binding Category}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="BookCode" Binding="{Binding BookCode}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="Inventory" Binding="{Binding Inventory}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="DateTaken" Binding="{Binding DateTaken}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="RecipientName" Binding="{Binding RecipientName}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="ReturnDate" Binding="{Binding ReturnDate}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="ReleaseDate" Binding="{Binding ReleaseDate}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="Language" Binding="{Binding BookLanguage}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="Length" Binding="{Binding Length}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="Form" Binding="{Binding Form}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="Translator" Binding="{Binding Translator}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="Narrator" Binding="{Binding Narrator}"/>  
                        <DataGridTextColumn x:Name="ISBN" Binding="{Binding ISBN}"/>  
                        <DataGridTextColumn x:Name="Location" Binding="{Binding Location}"/>  
                        <DataGridTextColumn x:Name="Price" Binding="{Binding Price}"/>  
                        <DataGridTemplateColumn x:Name="BookImage" Width="SizeToHeader">  
                            <DataGridTemplateColumn.CellTemplate>  
                                <DataTemplate>  
                                    <Image x:Name="BookImg" Source="{Binding BookImage}"/>  
                                </DataTemplate>  
                            </DataGridTemplateColumn.CellTemplate>  
                        </DataGridTemplateColumn>  
                    </DataGrid.Columns>  
                </DataGrid>  
            </Grid>  
        </ItemsControl>  
    </GroupBox>  
    <GroupBox x:Name="Members_GroupBox" Header="Members" Background="Transparent" Visibility="Visible" HorizontalAlignment="Center" Width="500" Height="400" VerticalAlignment="Center">  
        <GroupBox.Style>  
            <Style TargetType="{x:Type GroupBox}">  
                <Setter Property="BorderBrush" Value="DarkGray"/>  
                <Setter Property="BorderThickness" Value="1"/>  
                <Setter Property="Template">  
                    <Setter.Value>  
                        <ControlTemplate TargetType="{x:Type GroupBox}">  
                            <Grid SnapsToDevicePixels="true">  
                                <Grid.ColumnDefinitions>  
                                    <ColumnDefinition Width="*"/>  
                                    <ColumnDefinition Width="*"/>  
                                    <ColumnDefinition Width="*"/>  
                                    <ColumnDefinition Width="*"/>  
                                </Grid.ColumnDefinitions>  
                                <Grid.RowDefinitions>  
                                    <RowDefinition Height="*"/>  
                                    <RowDefinition Height="*"/>  
                                    <RowDefinition Height="*"/>  
                                    <RowDefinition Height="*"/>  
                                </Grid.RowDefinitions>  
                                <Border BorderBrush="DarkGray"   
                                BorderThickness="1"  
                                CornerRadius="9"  
                                Grid.ColumnSpan="4"   
                                Grid.RowSpan="4">  
                                    <Border.OpacityMask>  
                                        <MultiBinding ConverterParameter="9">  
                                            <MultiBinding.Converter>  
                                                <BorderGapMaskConverter/>  
                                            </MultiBinding.Converter>  
                                            <Binding ElementName="Header" Path="ActualWidth"/>  
                                            <Binding Path="ActualWidth" RelativeSource="{RelativeSource Self}"/>  
                                            <Binding Path="ActualHeight" RelativeSource="{RelativeSource Self}"/>  
                                        </MultiBinding>  
                                    </Border.OpacityMask>  
                                </Border>  
                                <Border x:Name="Header" Grid.RowSpan="1" Grid.ColumnSpan="2"  Margin="9,-11.5,0,0" HorizontalAlignment="Left" VerticalAlignment="Top">  
                                    <ContentPresenter  ContentSource="Header"  
                                              RecognizesAccessKey="True"   
                                              SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>  
                                </Border>  
                                <ContentPresenter  Grid.ColumnSpan="2" Grid.Column="1" Grid.Row="1"   
                                          Margin="{TemplateBinding Padding}"  
                                          SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>  
                            </Grid>  
                        </ControlTemplate>  
                    </Setter.Value>  
                </Setter>  
            </Style>  
        </GroupBox.Style>  
        <ItemsControl Width="486" Height="386" Margin="-118,-93,-118,-193">  
            <Grid DataContext="{StaticResource MemberTableViewSource}" Width="486" Height="386">  
                <DataGrid x:Name="MemberDataGrid" HeadersVisibility="Column" EnableRowVirtualization="False" AutoGenerateColumns="False" ItemsSource="{Binding}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="486" Height="386" Margin="0">  
                    <DataGrid.Columns>  
                        <DataGridTextColumn x:Name="FirstName" Binding="{Binding FirstName}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="LastName" Binding="{Binding LastName}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="DateOfBirth" Binding="{Binding DateOfBirth}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="IDNumber" Binding="{Binding IDNumber}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="PhoneNumber" Binding="{Binding PhoneNumber}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="MobilePhoneFirstNumber" Binding="{Binding MobilePhoneFirstNumber}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="MobilePhoneSecondNumber" Binding="{Binding MobilePhoneSecondNumber}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="LoanDate" Binding="{Binding LoanDate}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="NumberOfBooksBorrowed" Binding="{Binding NumberOfBooksBorrowed}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="NamesOfBorrowedBooks" Binding="{Binding NamesOfBorrowedBooks}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="BookReturnDate" Binding="{Binding BookReturnDate}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="MembershipDate" Binding="{Binding MembershipDate}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="RegistrationFee" Binding="{Binding RegistrationFee}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="QR" Binding="{Binding QR}" Width="auto"/>  
                        <DataGridTextColumn x:Name="Credit" Binding="{Binding Credit}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="Debt" Binding="{Binding Debt}" Width="SizeToHeader"/>  
                        <DataGridTextColumn x:Name="Description" Binding="{Binding Description}" Width="SizeToHeader"/>  
                        <DataGridTemplateColumn x:Name="MemberImage" Width="SizeToHeader">  
                            <DataGridTemplateColumn.CellTemplate>  
                                <DataTemplate>  
                                    <Image x:Name="MemberImg" Source="{Binding MemberImage}"/>  
                                </DataTemplate>  
                            </DataGridTemplateColumn.CellTemplate>  
                        </DataGridTemplateColumn>  
                    </DataGrid.Columns>  
                </DataGrid>  
            </Grid>  
        </ItemsControl>  
    </GroupBox>  

Thanks

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,690 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,411 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
772 questions
{count} votes