2016-05-16 56 views
0

我有一个DataGridView,它是以非常规方式创建的。它包含2列。第一个是标题,第二个是允许用户输入的列。第二列是DataGridViewCells和DataGridViewComboBoxCell的混合。 每行对DataGridViewCell允许的字符数有限制。限制DataGridViewCell中的字符数

我想要做的是在该单元格的KeyPress上限制可输入的字符数,并在长度大于限制时弹出消息。有没有人有这方面的任何示例代码。

我使用C#,Visual Studio 2010中

回答

1

如果你有一个列类型DataGridViewTextBoxColumn,你可以简单地设置属性MaxInputLength,这将限制输入文本的长度。

var column2 = new DataGridViewTextBoxColumn(); 
column2.MaxInputLength = 5; 
dataGridView.Columns.Add(column2); 

要手动添加代码为KeyPress事件处理程序请尝试以下操作:

TextBox columnTextBox; // Form field 

private void DataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) 
{ 
    if (columnTextBox != null) 
     columnTextBox.KeyPress -= TextBox_KeyPress; 
} 

private void DataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
{ 
    columnTextBox = e.Control as TextBox; 

    if (columnTextBox != null) 
     columnTextBox.KeyPress += TextBox_KeyPress; 
} 

private void TextBox_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    var textBox = (TextBox)sender; 
    // here your logic with textBox 
} 

设置事件处理程序DataGridView

dataGridView.EditingControlShowing += DataGridView_EditingControlShowing; 
dataGridView.CellEndEdit += DataGridView_CellEndEdit; 
+0

@ alexsander-petrov,我没有特定的DataGridViewTextBoxColumn列。我有一个DataGridView,然后我将2列添加到它。第一个是标题。第二个是用户输入数据的位置,但单元格的类型取决于动态创建的标题的字段类型。如果字段的字段类型是日期,则会创建日历单元格,或者如果它是只允许特定值的字符串,则会创建一个组合单元格单元格。 – MapMan