Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView restrict user input

Is it possible to restrict user input to DataGridView cell by means of RegEx? For example set format of cell input to something like this [0-9]{2} to forbid user enter something except 2 digits.

UPDATE Sorry, I was not very clear. I'm aware about CellValidation event and that I can check entered value after user input. But I wonder if I can prevent wrong user input before this event. I mean that user cannot input letters when cell regex is [0-9]. Is is possible?

like image 662
fat Avatar asked Mar 20 '13 06:03

fat


2 Answers

If you want to prevent invalid values as they're typed, you can handle the EditingControl.KeyPress event. Sample code below. You have to modify your regular expressions to allow incomplete values, though. And you should still use proper validation, because there are other ways to get data into the grid (such as copy paste).

    private string pattern = "^[0-9]{0,2}$";

    private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        dataGridView1.EditingControl.KeyPress -= EditingControl_KeyPress;
        dataGridView1.EditingControl.KeyPress += EditingControl_KeyPress;
    }

    private void EditingControl_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar))
        {
            Control editingControl = (Control)sender;
            if (!Regex.IsMatch(editingControl.Text + e.KeyChar, pattern))
                e.Handled = true;
        }
    }
like image 62
JosephHirn Avatar answered Sep 21 '22 18:09

JosephHirn


@Ginosaji , your code is good but with editingControl.Text + e.KeyChar you're assuming that user enters the last char at the end of the control text. What if the user places the char in the middle of the control somewhere?

like image 24
Batu.Khan Avatar answered Sep 20 '22 18:09

Batu.Khan