Results 1 to 4 of 4

Thread: [RESOLVED] How to limit text entry in DataGridView

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Feb 2009
    Posts
    258

    Resolved [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.

  2. #2
    Master Of Orion ForumAccount's Avatar
    Join Date
    Jan 2009
    Location
    Canada
    Posts
    2,802

    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

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Feb 2009
    Posts
    258

    Re: How to limit text entry in DataGridView

    Worked like a champ. Thanks.

  4. #4
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    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

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width