CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Dec 2005
    Location
    algiers, Algeria
    Posts
    132

    [RESOLVED] DataGridView cell restriction

    Hi, how i prevent the user from entering data other than numbers to a DataGridView cell ?

  2. #2
    Join Date
    May 2007
    Location
    Denmark
    Posts
    623

    Re: DataGridView cell restriction

    If you bind the datagridview to a collection of custom objects, the cells will be validated as the object's property types.

    For instance, if you have a datagridview which is bound to a generic list of Person objects. This class could have an integer property defined - let's call it Age. When editing a cell, the input will not be accepted as anything other than an int.

    Note, however, that committing another type, such as a string, will cause the datagridview's DataError event to be raised.

    Hope it helps
    It's not a bug, it's a feature!

  3. #3
    Join Date
    Dec 2005
    Location
    algiers, Algeria
    Posts
    132

    Resolved Re: DataGridView cell restriction

    thanks foamy, i found this solution :
    Code:
    ...
    this.dataGridView1.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.DataGridView1EditingControlShowing);
    ...
            void DataGridView1EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
            {
                if(e.Control is TextBox)
                {
                     TextBox tb = e.Control as TextBox;
                     tb.KeyPress -= new KeyPressEventHandler(tb_KeyPress);
                    if (this.dataGridView1.CurrentCell.ColumnIndex != 0)
                    {
                        tb.KeyPress += new KeyPressEventHandler(tb_KeyPress);
                    }
                }
            }
            
            void tb_KeyPress(object sender, KeyPressEventArgs e)
            {
                if (!(char.IsDigit(e.KeyChar)))
                {
                        e.Handled = true;
                }
            }
    Last edited by ledaker; January 22nd, 2009 at 03:45 PM.

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

Featured