简体   繁体   中英

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?

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;
        }
    }

@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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM