C# 如何设置datagridview列的最大长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12903087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:54:17  来源:igfitidea点击:

How to set max length of datagridview column

c#datagridview

提问by Jim Lahman

I have a DataGridViewwhere the units can be entered in a TextBoxcolumn.

我有一个DataGridView可以在TextBox列中输入单位的地方。

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

如何将此列的输入长度限制6字符?

采纳答案by Jay Riggs

Use the MaxInputLengthproperty of the DataGridViewTextBoxColumn.

使用 的MaxInputLength属性DataGridViewTextBoxColumn

This property is available through the Designer or through code:

此属性可通过设计器或通过代码获得:

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

回答by Andrii Kalytiiuk

Please use CellValueChangedevent of DataGridView.

请使用DataGridView 的CellValueChanged事件。

In the handler of the event you can check ColumnIndexand RowIndexproperties of DataGridViewCellEventArgsargument 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 DataGridViewfield is to modify respective grid column properties. Properties of grid columns can be altered on Edit Columnsform that is invoked for grid control in form designerwith right click menu item Edit Columns...:

如其他答案所述 - 限制DataGridView字段文本长度的最自然方法是修改相应的网格列属性。网格列的属性可以在Edit Columns表单上更改,该表单表单设计器中使用右键单击菜单项Edit Columns...为网格控件调用:

enter image description here

在此处输入图片说明