Reputation: 668
I have a DataGridView, that is created dyanically. It contains 2 columns. The first being the header and the second column is the one that allows user input. The 2nd column is a mixture of DataGridViewCells and DataGridViewComboBoxCell. Each row has a limit on the number of characters that are allowed within the DataGridViewCell.
What i would like to do is on KeyPress for that cell limit the number of characters that can be entered and popup a message if the length is greater than the limit. Does anyone have any example code for this.
I am using c#, Visual Studio 2010
Upvotes: 1
Views: 3192
Reputation: 14231
If you have a column type of DataGridViewTextBoxColumn
, you can simply set the property MaxInputLength
that would limit the length of the input text.
var column2 = new DataGridViewTextBoxColumn();
column2.MaxInputLength = 5;
dataGridView.Columns.Add(column2);
To manually add code for the KeyPress
event handler try the following:
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
}
Set event handlers for DataGridView
:
dataGridView.EditingControlShowing += DataGridView_EditingControlShowing;
dataGridView.CellEndEdit += DataGridView_CellEndEdit;
Upvotes: 2
Reputation: 36
You can build your own DatagridViewColumn Class i think. Take a look at this: http://msdn.microsoft.com/en-us/library/ms180996.aspx
Upvotes: 0