How to generate a report from ListView on WPF?

B M-A 361 Reputation points
2023-05-28T21:29:58.0733333+00:00

Hello !

I want to generate an Listview, based on another Listview, by moving items from first Listview to the second one and generate a report based on my second ListView and Sum the price.

My first Listview is something like this:

[id] [product] [price]

1 ----- car -------1000

2 ----- toy ------- 10

3 ----- apple ------- 5

The second ListView is like this :

[id] [product] [price]

1 ----- car -------1000

2 ----- toy ------- 10

3 ----- apple ------- 5

2 ----- toy ------- 10

3 ----- apple ------- 5

Best regards,

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,308 questions
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,657 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,144 questions
0 comments No comments
{count} votes

Accepted answer
  1. Hui Liu-MSFT 34,541 Reputation points Microsoft Vendor
    2023-05-29T06:49:28.66+00:00

    Hi,@B M-A. Welcome Microsoft Q&A. For selecting Item from the first ListView to the second ListView, and generate a report based on the second ListView and Sum the price, you could refer to the following code.

     <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <ListView Grid.Column="0" ItemsSource="{Binding View1}"  SelectedItem="{Binding LeftRow}"
                   >
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="ID" DisplayMemberBinding="{Binding Id}" />
                        <GridViewColumn Header="Product" DisplayMemberBinding="{Binding Product}" />
                        <GridViewColumn Header="Price" DisplayMemberBinding="{Binding Price}" />
                    </GridView>
                </ListView.View>
            </ListView>
            <StackPanel Grid.Column="1" Orientation="Vertical" HorizontalAlignment="Center">
                <Button Grid.Row="1" Content="&gt;" Command="{Binding MoveToSelectedCommand}" CommandParameter="ToSelected" Margin="10" Width="100"/>
                <Button Grid.Row="1" Grid.Column="1" Content="&lt;" Command="{Binding MoveToSourceCommand}" CommandParameter="ToSource" Margin="10" Width="100"/>
               
                <Button Content="generate report ;" Width="50" Command="{Binding GenerateReportCommand}" CommandParameter="{Binding ElementName=SelectedListView}" />
            </StackPanel>
            <ListView Grid.Column="2" ItemsSource="{Binding View2}"  SelectedItem="{Binding RightRow}"
                   x:Name="SelectedListView">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="ID" DisplayMemberBinding="{Binding Id}" />
                        <GridViewColumn Header="Product" DisplayMemberBinding="{Binding Product}" />
                        <GridViewColumn Header="Price" DisplayMemberBinding="{Binding Price}" />
                    </GridView>
                </ListView.View>
            </ListView>
        </Grid>
    
    
    
    

    Codebedhind:

     public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                DataContext=new MainViewModel();
            }
        }
        public class MainViewModel : INotifyPropertyChanged
        {
            private ObservableCollection<Item> sourceItems;
            private ObservableCollection<Item> selectedItems;
            private CollectionViewSource cvs1 = new();
            private CollectionViewSource cvs2 = new();
            public ICollectionView View1 { get => cvs1.View; }
            public ICollectionView View2 { get => cvs2.View; }
            public Item LeftRow { get; set; }
            public Item RightRow { get; set; }
            public ICommand MoveToSelectedCommand { get; }
            public ICommand MoveToSourceCommand { get; }
            public ICommand GenerateReportCommand { get; }
         
            public ICommand MyCommand { get; }
            public MainViewModel()
            {
                sourceItems = new ObservableCollection<Item>
            {
                new Item { Id = 1, Product = "Car", Price = 1000 },
                new Item { Id = 2, Product = "Toy", Price = 10 },
                new Item { Id = 3, Product = "Apple", Price = 5 }
            };
    
                selectedItems = new ObservableCollection<Item>();
                cvs1.Source = sourceItems;
                cvs2.Source = selectedItems;
                MoveToSelectedCommand = new RelayCommand(MoveToSelected);
                MoveToSourceCommand = new RelayCommand(MoveToSource);
                GenerateReportCommand = new RelayCommand(GenerateReport);
    
            }
            private void GenerateReport(object parameter)
            {
                StringBuilder reportBuilder = new StringBuilder();
                decimal totalPrice = 0;
    
                foreach (var item in selectedItems)
                {
                    reportBuilder.AppendLine($"Product: {item.Product}, Price: {item.Price}");
                    totalPrice += item.Price;
                }
    
                reportBuilder.AppendLine($"Total Price: {totalPrice}");
    
                string report = reportBuilder.ToString();
                MessageBox.Show(report, "Report");
            }
         
            private void MoveToSelected(object parameter)
            {
                if(parameter.ToString() == "ToSelected")
                {
                   
                    if (LeftRow != null)
                    {
                        Item d = LeftRow;
                        selectedItems.Add(d);
                    }
                }
              
            }
            
    
            private void MoveToSource(object parameter)
            {
                if (parameter.ToString() == "ToSource")
                {
                    if (RightRow != null)
                    {
                        Item d = RightRow;
    
                        selectedItems.Add(d);
                    }
                }
                   
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    
        public class Item
        {
            public int Id { get; set; }
            public string Product { get; set; }
            public decimal Price { get; set; }
        }
    
       
        public class RelayCommand : ICommand
        {
            private readonly Action<object> _execute;
            private readonly Predicate<object> _canExecute;
    
            public RelayCommand(Action<object> execute)
                : this(execute, null)
            {
            }
    
            public RelayCommand(Action<object> execute, Predicate<object> canExecute)
            {
                if (execute == null)
                    throw new ArgumentNullException("execute");
                _execute = execute;
                _canExecute = canExecute;
            }
    
            public bool CanExecute(object parameter)
            {
                return _canExecute == null ? true : _canExecute(parameter);
            }
    
            public event EventHandler CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }
    
            public void Execute(object parameter)
            {
                _execute(parameter);
            }
        }
    
    
    
    

    The result:

    4


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful