我有一个DataGridView,它是以非常规方式创建的。它包含2列。第一个是标题,第二个是允许用户输入的列。第二列是DataGridViewCells和DataGridViewComboBoxCell的混合。 每行对DataGridViewCell允许的字符数有限制。限制DataGridViewCell中的字符数
我想要做的是在该单元格的KeyPress上限制可输入的字符数,并在长度大于限制时弹出消息。有没有人有这方面的任何示例代码。
我使用C#,Visual Studio 2010中
我有一个DataGridView,它是以非常规方式创建的。它包含2列。第一个是标题,第二个是允许用户输入的列。第二列是DataGridViewCells和DataGridViewComboBoxCell的混合。 每行对DataGridViewCell允许的字符数有限制。限制DataGridViewCell中的字符数
我想要做的是在该单元格的KeyPress上限制可输入的字符数,并在长度大于限制时弹出消息。有没有人有这方面的任何示例代码。
我使用C#,Visual Studio 2010中
你可以建立自己的DataGridViewColumn类,我认为。看看这个:http://msdn.microsoft.com/en-us/library/ms180996.aspx
如果你有一个列类型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;
@ alexsander-petrov,我没有特定的DataGridViewTextBoxColumn列。我有一个DataGridView,然后我将2列添加到它。第一个是标题。第二个是用户输入数据的位置,但单元格的类型取决于动态创建的标题的字段类型。如果字段的字段类型是日期,则会创建日历单元格,或者如果它是只允许特定值的字符串,则会创建一个组合单元格单元格。 – MapMan
是否有可能为你考虑其中一个工作实例你的答案中的** KeyPress **事件处理程序的? –