[RESOLVED] How to limit text entry in DataGridView
Okay, I've got a datagridview in my WinForms app that auto-builds the column list from a datatable schema. It's working fine, except that it allows the user to enter values too long for the database field. For example, I have a "name" field that is defined in the Sql-Server database as a varchar(50). Is there any way to limit that cell (column?) so that it only accepts 50 characters? Right now it lets them enter anything and throws an exception later.
I know this can be done with a textbox, merely by setting the MaxLength property... but I'm not seeing anything that lets me do the same thing with the control in a datagridview column.
Any help is appreciated.
Re: How to limit text entry in DataGridView
Try this:
Code:
Public Class Form1
Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, _
ByVal e As DataGridViewEditingControlShowingEventArgs) _
Handles DataGridView1.EditingControlShowing
Dim tb = TryCast(e.Control, TextBox)
If tb IsNot Nothing Then
tb.MaxLength = 50
End If
End Sub
End Class
Re: How to limit text entry in DataGridView
Worked like a champ. Thanks.
Re: [RESOLVED] How to limit text entry in DataGridView
Even thou you have a solution I want to present an alternate.
Get the column schema for the table then use the name and length for the column to set the max length the column can be when editing in a DataGridView.
Example, you got the column information for a field LastName which has a max length of 50. Of course in the example below the 50 would be from the column schema
Code:
CType(DataGridView1.Columns("LastName"), _
DataGridViewTextBoxColumn).MaxInputLength = 50
MSDN For getting schema inforamtion
http://support.microsoft.com/kb/309488