12

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?

Andrii Kalytiiuk
  • 1,501
  • 14
  • 26
Jim Lahman
  • 2,691
  • 2
  • 25
  • 21

4 Answers4

27

Use the MaxInputLength property of the DataGridViewTextBoxColumn.

This property is available through the Designer or through code:

((DataGridViewTextBoxColumn)dataGridView1.Columns[yourColumn]).MaxInputLength = 6;
Jay Riggs
  • 53,046
  • 9
  • 139
  • 151
  • Thanks; used your suggestion and works great! -> `private void dgAPB_CellEnter(object sender, DataGridViewCellEventArgs e) {((DataGridViewTextBoxColumn)dgAPB.Columns[1] = 6;}` – Jim Lahman Oct 15 '12 at 20:36
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...:

enter image description here

Andrii Kalytiiuk
  • 1,501
  • 14
  • 26
0

You may have to play with cell-edit events. http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvaluechanged.aspx

sgud
  • 422
  • 2
  • 7
0

You don't necessarily have the columns ready to manipulate if you're using data binding. For data binding, using the ColumnAdded listener can help:

public FormSingleValidation(BindingList<ValidateSingle> validateSingles)
{
    InitializeComponent();

    dataGridViewSingleValidation.ColumnAdded += ColumnAdded;

    this.validateSingles = validateSingles;
    var source = new BindingSource(validateSingles, null);
    dataGridViewSingleValidation.DataSource = source;
}

private void ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
    if(e.Column.GetType() == typeof(DataGridViewTextBoxColumn))
    {
        DataGridViewTextBoxColumn column = (DataGridViewTextBoxColumn) e.Column;
        column.MaxInputLength = 6;
    }
}

Caveats

  1. Obviously this applies to all text columns without discrimination, you can add a conditional filter using the column's name if you only want specific columns to be effected.
Waleed Al Harthi
  • 705
  • 9
  • 25