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?
Use the MaxInputLength
property of the DataGridViewTextBoxColumn
.
This property is available through the Designer or through code:
((DataGridViewTextBoxColumn)dataGridView1.Columns[yourColumn]).MaxInputLength = 6;
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...:
You may have to play with cell-edit events. http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvaluechanged.aspx