Tell me, please, is it possible to restrict text input to a cell (or to all cells) of a DataGridView with a certain set of characters?

For example, in order to be able to enter only the letters [az], the numbers [0-9] and the signs "-" and "/".

1 answer 1

Thanks UserName for the hint. The desired effect can be achieved through the DataGridView.CellValidating event and using regular expressions.

Code:

private void DataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { const string disallowed = @"[^0-9A-Za-z-\/]"; var newText = Regex.Replace(e.FormattedValue.ToString(), disallowed, string.Empty); dataGridView1.Rows[e.RowIndex].ErrorText = ""; if (dataGridView1.Rows[e.RowIndex].IsNewRow) return; if (string.CompareOrdinal(e.FormattedValue.ToString(), newText) == 0) return; e.Cancel = true; dataGridView1.Rows[e.RowIndex].ErrorText = "Некорректный символ!"; } 

Result:

Result