DataGridView KeyPress event

DataGridView limited to number input

Page 1 of 1

1 Replies - 7016 Views - Last Post: 22 September 2009 - 02:04 AM Rate Topic: -----

#1 Pajolo  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 22-September 09

DataGridView KeyPress event

Posted 22 September 2009 - 12:42 AM

Hey all,
first time posting, so hopefully I'll get lucky.

I have written this method to filter input to textboxes and only allow binary:

private void binaryInput_KeyPress(object sender, KeyPressEventArgs e)
{
   // Binary and functions only!
   if(e.KeyChar.ToString() != "1" && e.KeyChar.ToString() != "0" && !Char.IsControl(e.KeyChar))
   e.Handled = true;
}


Works like a dream!
Now I'm trying to implement it for DataGridView.
This class also has the KeyPressedEvent, but for some reason it doesn't invoke the event when a key is pressed to edit a Cell.
Any givers?
Thanks a mil
Paul

Is This A Good Question/Topic? 0
  • +

Replies To: DataGridView KeyPress event

#2 janne_panne  Icon User is offline

  • WinRT Dev
  • member icon

Reputation: 428
  • View blog
  • Posts: 1,047
  • Joined: 09-June 09

Re: DataGridView KeyPress event

Posted 22 September 2009 - 02:04 AM

Here is one way:

		public Form1() {
			InitializeComponent();

			dataGridView1.Rows.Add(1, "asdf");
			dataGridView1.Rows.Add(2, "qwer");
			dataGridView1.Rows.Add(3, "zxcv");
			
			// use EditingControlShowing method to get the control which is getting edited
			dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);
		}

		void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) {
			// set KeyPress event for the control which is edited
			e.Control.KeyPress += new KeyPressEventHandler(Control_KeyPress);
		}

		void Control_KeyPress(object sender, KeyPressEventArgs e) {
			// KeyPress logic here
			if (e.KeyChar == (char)Keys.A) {
				e.Handled = true;
				return;
			}
		}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1