0

the database I'm connecting my app for the "percent" column is using values less than 1 (i.e 15% is stored as 0,15 in the database), so I'm using the Format = ".00%" to display the values in the DataGrid column.

Question is How to properly let users insert the values bigger than 1 - to write i.e. 50 or 50% in the cell - and transform it to 0,5 in the database.

I was looking for DataGridViewCellValidatingEventHandler and added the Event levDGV_PercentCellValidating, but I don't know how to change the values...

private void levDGV_PercentCellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{

    string dataPropertyName = levDGV.Columns[e.ColumnIndex].DataPropertyName; // deliveryProcent
    // Abort validation if cell is not in the "deliveryProcent" column.
    if (!dataPropertyName.Equals("deliveryProcent")) return;
    levDGV.Rows[e.RowIndex].ErrorText = "";

    string testValue = e.FormattedValue.ToString();
    char lastChar = testValue[testValue.Length - 1];
    if (lastChar == (char)37)
    {
        //TODO: Remove % character from entered string
    }
    //TODO: divide the value by 100 and set as currentCell value
}

how to transform entered value to the properly validated one (divided by 100)?

mallorn
  • 735
  • 1
  • 6
  • 10
  • After reading this: https://stackoverflow.com/questions/4742960/datagridview-validation-changing-cell-value I think I'll go for CellParsing... – mallorn Oct 21 '17 at 21:00

1 Answers1

0

Leaving the solution for others, the Parsing which seems to work for me:

private void levDGV_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
        {
            string dataPropertyName = levDGV.Columns[e.ColumnIndex].DataPropertyName;
            if (dataPropertyName.Equals("deliveryProcent"))
            {
                if (e.Value != null)
                {
                    try
                    {
                        string testValueStr = e.Value.ToString();
                        char lastChar = testValueStr[testValueStr.Length - 1];
                        if (lastChar == (char)37)
                        {
                            //Remove % character from entered string
                            testValueStr = testValueStr.Substring(0, testValueStr.Length - 1);
                        }
                        //divide the value by 100 and set as currentCell value
                        double testValue = (Convert.ToDouble(testValueStr)) / 100;
                        e.Value = testValue;
                        e.ParsingApplied = true;
                    }
                    catch (FormatException)
                    {
                        // Set to false in case another CellParsing handler
                        // wants to try to parse this DataGridViewCellParsingEventArgs instance.
                        e.ParsingApplied = false;
                    }
                }

            }
        }
mallorn
  • 735
  • 1
  • 6
  • 10