hectormtnezg
hectormtnezg

Reputation: 132

DataGrid Multiplicating Two Columns

I'm in need of the community's help. I am trying to multiply the values of two columns in a DataGrid (WPF and C#), the first column get its data from a MySql database and the second column is an input value where a user will type a number which should be multiplied with the first column and the result should be displayed in a third column called "Total". I have searched all over and tried different approaches from other people who tried the nearly same thing but I just can't get the value to multiply and the result to appear in the third column. Here's the last bit of code I've tried, I have to mention that I am still very new to C# and WPF with not so much experience:

<DataGrid AutoGenerateColumns="False" x:Name="tblData" Margin="30,197,7,0" Grid.Row="1" VerticalAlignment="Top" Height="510" Grid.ColumnSpan="4"
              BorderThickness="2" BorderBrush="#FF445BBF" ItemsSource="{Binding Path=LoadDataBinding}" CanUserResizeRows="False" ClipToBounds="True"
              CanUserSortColumns="False" HorizontalGridLinesBrush="#FFC7C7C7" VerticalGridLinesBrush="#FFC7C7C7" IsManipulationEnabled="True" EnableRowVirtualization="False" 
              IsTextSearchEnabled="True" xmlns:local="clr-namespace:PoS_Pimentel">
        <DataGrid.Resources>
            <local:AmmountConverter x:Key="AmmountConverter" />
        </DataGrid.Resources>
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path=nomprod}" Header="Producto" Width="500" IsReadOnly="True">
                <DataGridTextColumn.HeaderStyle>
                    <Style TargetType="DataGridColumnHeader">
                        <Setter Property="HorizontalContentAlignment" Value="Center" />
                        <Setter Property="FontSize" Value="14" />
                    </Style>
                </DataGridTextColumn.HeaderStyle>
            </DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Path=preciogram, Mode=TwoWay}" Header="Precio por Gramo" Width="190" IsReadOnly="True">
                <DataGridTextColumn.HeaderStyle>
                    <Style TargetType="DataGridColumnHeader">
                        <Setter Property="HorizontalContentAlignment" Value="Center" />
                        <Setter Property="FontSize" Value="14" />
                    </Style>
                </DataGridTextColumn.HeaderStyle>
            </DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Path=gramos, Mode=TwoWay}" Header="Gramos" Width="190" IsReadOnly="False">
                <DataGridTextColumn.HeaderStyle>
                    <Style TargetType="DataGridColumnHeader">
                        <Setter Property="HorizontalContentAlignment" Value="Center" />
                        <Setter Property="FontSize" Value="14" />
                    </Style>
                </DataGridTextColumn.HeaderStyle>
            </DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Path=total, Mode=TwoWay}" Header="Total" Width="*" IsReadOnly="True">
                <DataGridTextColumn.HeaderStyle>
                    <Style TargetType="DataGridColumnHeader">
                        <Setter Property="HorizontalContentAlignment" Value="Center" />
                        <Setter Property="FontSize" Value="14" />
                    </Style>
                </DataGridTextColumn.HeaderStyle>
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>

and on the C# end I created two separate .cs file for an EntitiyClass and an AmmountConverter class:

EntityClass code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Windows.Forms;

namespace PoS
{
    #region
    public class Entity_Class : INotifyPropertyChanged
    {
        private int _preciogram;
        public int PrecioGram
        {
            get { return _preciogram; }
            set { _preciogram = value; NotifyPropertyChanged("gramos"); }
        }

        private int _gramos;
        public int Gramos
        {
            get { return _gramos; }
            set { _gramos = value; NotifyPropertyChanged("gramos"); }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string propertyName)
        {
            if(PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

And the AmmountConverter class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace PoS_Pimentel
{
    public class AmmountConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            double prcgrms = values[1] == null ? 0 : System.Convert.ToDouble(values[1]);
            double grms = values[2] == null ? 0 : System.Convert.ToDouble(values[2]);

            return prcgrms * grms;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

I'm not very good at this but I am trying and any pointers will be greatly appreciated. Thank you all.

Upvotes: 1

Views: 2602

Answers (2)

Rachel
Rachel

Reputation: 132588

There are two ways to accomplish this, and it looks like you're trying to use a mix of both.

One method is to bind all 3 columns to properties on your data object, and use a PropertyChange event handler on the user-entered property that re-calculates the total column. This is usually my preference.

<DataGridTextColumn Binding="{Binding Value1}" />
<DataGridTextColumn Binding="{Binding Value2}" />
<DataGridTextColumn Binding="{Binding Total}" />
private void MyDataItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "Value2")
        Total = Value1 * Value2;
}

With this approach, no converter is needed.


The other approach is to not bind the 3rd column, and to use a converter to display it

<!-- Note: syntax may be incorrect here -->
<DataGridTextColumn Binding="{Binding Value1}" />
<DataGridTextColumn Binding="{Binding Value2}" />
<DataGridTextColumn>
    <DataGridTextColumn.Binding>
        <Multibinding Converter="{StaticResource MyMultiplicationConverter}">
            <Binding Path="Value1" />
            <Binding Path="Value2" />
        </Multibinding>
    <DataGridTextColumn.Binding>
</DataGridTextColumn>

In this case, we are binding two columns to values on the data model, and the 3rd column is using a converter to convert the two values to a different 3rd value.


It should be noted that regardless of which approach you use, the default binding mode for a TextBox is to only update the source on LostFocus, so we don't raise excessive change notifications. If you want it to update in real-time as the user enters data, you should change the binding mode to be PropertyChanged, or write your own binding update behavior to update the bound source after a short delay.

Also as a side note, you're raising the PropertyChange notification for the wrong property in your PrecioGram property :

public int PrecioGram
{
    get { return _preciogram; }
    set 
    { 
        _preciogram = value; 
        NotifyPropertyChanged("gramos"); // Incorrect property here
    }
}

Upvotes: 1

Ayyappan Subramanian
Ayyappan Subramanian

Reputation: 5366

You dont need to use a converter for doing this calculation. Hope you can handle it in Model Class. Also You need to bind to property. DataGrid binding property Names are not correct c# is case sensitive. Refer my below code.

 <DataGrid x:Name="dgr" AutoGenerateColumns="False" ItemsSource="{Binding LoadDataBinding}">           
        <DataGrid.Columns>                
            <DataGridTextColumn Binding="{Binding Path=PrecioGram, Mode=TwoWay}" Header="Precio por Gramo" Width="190" IsReadOnly="True">
                <DataGridTextColumn.HeaderStyle>
                    <Style TargetType="DataGridColumnHeader">
                        <Setter Property="HorizontalContentAlignment" Value="Center" />
                        <Setter Property="FontSize" Value="14" />
                    </Style>
                </DataGridTextColumn.HeaderStyle>
            </DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Path=Gramos, Mode=TwoWay}" Header="Gramos" Width="190" IsReadOnly="False">
                <DataGridTextColumn.HeaderStyle>
                    <Style TargetType="DataGridColumnHeader">
                        <Setter Property="HorizontalContentAlignment" Value="Center" />
                        <Setter Property="FontSize" Value="14" />
                    </Style>
                </DataGridTextColumn.HeaderStyle>
            </DataGridTextColumn>
            <DataGridTextColumn Header="Total" Width="100" Binding="{Binding Total}">
                <DataGridTextColumn.HeaderStyle>
                    <Style TargetType="DataGridColumnHeader">
                        <Setter Property="HorizontalContentAlignment" Value="Center" />
                        <Setter Property="FontSize" Value="14" />
                    </Style>
                </DataGridTextColumn.HeaderStyle>

            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>

 public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new MainViewModel();
    }

}

public class MainViewModel
{
    private ObservableCollection<Entity_Class> myVar = new ObservableCollection<Entity_Class>();

    public ObservableCollection<Entity_Class> LoadDataBinding
    {
        get { return myVar; }
        set { myVar = value; }
    }

    public MainViewModel()
    {
        for (int i = 1; i < 10; i++)
        {
            LoadDataBinding.Add(new Entity_Class() { PrecioGram=i});
        }
    }
}   

public class Entity_Class : INotifyPropertyChanged
{
    private int _preciogram;
    public int PrecioGram
    {
        get { return _preciogram; }
        set { _preciogram = value; NotifyPropertyChanged("PrecioGram"); }
    }

    private int _gramos;
    public int Gramos
    {
        get { return _gramos; }
        set
        { 
            _gramos = value; NotifyPropertyChanged("gramos");
            Total = _preciogram * _gramos;
        }
    }

    private int _total;
    public int Total
    {
        get { return _total; }
        set { _total = value; NotifyPropertyChanged("Total"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Upvotes: 3

Related Questions