开发者

How to prevent bad formatted data input in DataGridViewCell

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 开发者_JAVA技巧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;
            }
        }

    }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜