C# .NET 3.5 GridView Blunders, how to validate and replace a value

Some days I wonder to myself, really Microsoft what were you thinking?  Or is the problem I am not thinking either way I ran into an issue this evening that just frustrated me like no other, so I thought I had best share what my solution was.

I am working on an application to organize my recipe collection and publish it online, no shock, I even code in food.  Anyhow, in order to put measurements into the application I am using a DataGridView and put the measurements in like 1 3/4 or 2/3, the idea was that on save those numbers would then be converted to decimals and saved in the database.  This is where my problem began when I bound my DataGridView to my data from my Stored Procedure, pandamoniam.  The DataGridView then expected that all the input would be in decimal format, so I decided to capture the validating event for that cell which ended up looking like this:

1
2
3
4
5
6
7
8
9
        private void dgvIngredients_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            //this is the amount column
            if (e.ColumnIndex == 0)
            {
                dgvIngredients.CancelEdit();
                dgvIngredients[e.ColumnIndex, e.RowIndex].Value = parseFraction(e.FormattedValue.ToString().Trim());   
            }
        }

Now this worked awesome for the first row in the DataGridView however, subsequent new rows in the DataGridView resulted in blanks when the validation completed, most frustrating.  So after hours of threatening my computer with harm. I arrived at a solution although not as graceful as I had hoped, I needed to intervene on one more event, the RowsAdded event as follows:

1
2
3
4
        private void dgvIngredients_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            dgvIngredients.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }

And BAM it works.  Not exactly what I had in mind but better then converting fractions to decimals by hand.

Tagged with: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Top