简体   繁体   English

如何设置datagridview列的最大长度

[英]How to set max length of datagridview column

I have a DataGridView where the units can be entered in a TextBox column.我有一个DataGridView ,可以在TextBox列中输入单位。

How do I restrict the input length of this column to 6 characters?如何将此列的输入长度限制6字符?

Use the MaxInputLength property of the DataGridViewTextBoxColumn . 使用DataGridViewTextBoxColumnMaxInputLength属性。

This property is available through the Designer or through code: 此属性可通过Designer或代码获得:

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

Please use CellValueChanged event of DataGridView . 请使用DataGridView的 CellValueChanged事件。

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. 在事件的处理程序中,您可以检查DataGridViewCellEventArgs参数的ColumnIndexRowIndex属性,以识别编辑网格的感兴趣字段,然后 - 采取适当的操作。

As stated in other answers - most natural way to restrict text lengths for DataGridView field is to modify respective grid column properties. 如其他答案中所述 - 限制DataGridView字段的文本长度的最自然方式是修改相应的网格列属性。 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 don't necessarily have the columns ready to manipulate if you're using data binding.如果您使用数据绑定,则不一定要准备好操作的列。 For data binding, using the ColumnAdded listener can help:对于数据绑定,使用ColumnAdded侦听器可以帮助:

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.显然,这适用于所有文本列,不加区分,如果您只希望影响特定列,则可以使用列名添加条件过滤器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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