12
votes

I have a DataGridView where the units can be entered in a TextBox column.

How do I restrict the input length of this column to 6 characters?

3

3 Answers

27
votes

Use the MaxInputLength property of the DataGridViewTextBoxColumn.

This property is available through the Designer or through code:

((DataGridViewTextBoxColumn)dataGridView1.Columns[yourColumn]).MaxInputLength = 6;
6
votes

Please use CellValueChanged event of DataGridView.

In the handler of the event you can check ColumnIndex and RowIndex properties of DataGridViewCellEventArgs argument to identify that grid's field of interest is edited and then - take appropriate actions.

As stated in other answers - most natural way to restrict text lengths for DataGridView field is to modify respective grid column properties. Properties of grid columns can be altered on Edit Columns form that is invoked for grid control in form designer with right click menu item Edit Columns...:

enter image description here