1
votes

The DataGrid column is bind to a DataTable column with a decimal data type that is filled from the database.

<DataGridTextColumn Binding="{Binding Pay, UpdateSourceTrigger=PropertyChanged,Mode=TwoWay, Header="Sum"/>

After changing each cell I need to calculate the sum in the column.

private void dgPays_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) {
        if (dtPay == null || dtPay.Rows.Count == 0) {
            return;
        }
        decimal Pay;
        DataRow[] rr = dtPay.Select("IsTotal=1");
        foreach (DataRow r in rr) {
            dtPay.Rows.Remove(r);
        }

        Decimal.TryParse(dtPay.Compute("SUM(Pay)", "").ToString(), out Pay);
        dtPay.Rows.Add(null, null, null, null, null, null, Pay, null, true);
    }

But, when the user enters a negative fractional number with a leading zero "-0.xxxx" because of this binding, minus is lost at the time of input and "-0" is converted to "0". Such numbers can be entered only as "-.xxxx" which are automatically converted to "-0.xxxx", but it is inconvenient for the user.

The DataTable is filled from the database and then the values are saved from it to the database and I cannot change the "Mode=TwoWay" binding. If i change "UpdateSourceTrigger=PropertyChanged" does not work "dtPay.Compute("SUM(Pay)", "")" after Cell Edit Ending.

How to enter "-0" ?

1
Did you try the answer to: stackoverflow.com/questions/24230085/…J.H.

1 Answers

0
votes

Problem solved Initially changed the format of the cell

DataGridTextColumn Binding="{Binding Pay,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay,StringFormat={}{0:+#;-#;''}, Converter={StaticResource decimalConverter}}" Header="Sum" IsReadOnly="False"/>

And added Converter

public class DecimalConverter : IValueConverter {
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        if (value != null) {
            return value.ToString().Replace(",", lib.csGlobals.numSep).Replace(".", lib.csGlobals.numSep);
        }
        return Binding.DoNothing;
    }

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        string data = (value as string).Replace(",", lib.csGlobals.numSep).Replace(".", lib.csGlobals.numSep); 
        if (data == null) {
            return value;
        }
        if (data.Equals(string.Empty)) {
            return 0;
        }
        if (!string.IsNullOrEmpty(data)) {
            decimal result;

            if (data.EndsWith(".") || data.Equals("-0") || data.Equals("-") || data.EndsWith(",")
                || data.Equals("-0.0") || data.Equals("-0,0")
                ) {
                return Binding.DoNothing;
            }
            if (decimal.TryParse(data, out result)) {
                return result;
            }
        }
        return Binding.DoNothing;
    }
}