views:

27

answers:

1

I have an automatically binded DataGridView that obtains data and update data directly from a Strongly Typed Dataset and its TableAdapter.

the DataGridView allows data editing but I'm having issues dealing with bad formatted data input.

For example, one of the columns is a date, formatted in the database as datetime, 11/05/2010. You can edit the date and the DataGridView opens a TextBox in which you can enter letters, simbols and other unauthorised characters. When you finish editing the cell if has such bad data it throws a System.FormatException

How can I prevent some data to be entered?

Is there a way to "filter" that data before it is sent back to the DataGridView?

=========================================================================

As Alan said, the key was to handle the cellValidating event. I'll attach some code that helps to handle the value:

public static void CellValidating(object sender, System.Windows.Forms.DataGridViewCellValidatingEventArgs e)
    {

        string newValue = e.FormattedValue.ToString();
        string oldValue = ((System.Windows.Forms.DataGridView)(sender)).Rows[e.RowIndex].Cells[e.ColumnIndex].FormattedValue.ToString();

        //i like to check that the value has changed before validating it
        if (newValue != oldValue)    
        {
            if (false)//replace this with actual validation.        
            {
                //if data not valid cancel validation
                e.Cancel= true;
            }
        }

    }
+1  A: 

There are Row/CellValidating events on the DataGridView, you can use these to validate input and cancel the event if input is invalid - this leaves the row/cell in edit mode.

Adam
Thanks, that worked :)
Juan Nunez