[英]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
. 使用DataGridViewTextBoxColumn
的MaxInputLength
属性。
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参数的ColumnIndex和RowIndex属性,以识别编辑网格的感兴趣字段,然后 - 采取适当的操作。
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 may have to play with cell-edit events. 您可能必须使用单元格编辑事件。 http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvaluechanged.aspx http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvaluechanged.aspx
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注意事项
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.