Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
As I am typing a value into a cell of the datagridview in winform, I would like to check the value entered.
For example in a cell of the datagridview I enter 3 and then m
I basically would like to see if the user has entered m or t and if so multiply the number by 1000000 or 1000 respectively.
Is there an event to check for the text AS it is being entered into the cell?
Thanks
Posted
Updated 27-Sep-11 4:50am
v2

You can use KeyDown event to read through the characters being entered as they are being entered by the user.
This can be done with some manipulation like mentioned in this article:
http://social.msdn.microsoft.com/Forums/en/winformsdatacontrols/thread/db486d50-48f3-405d-bc7a-ad3720d4dd57[^]
 
Share this answer
 
v2
Comments
arkiboys 27-Sep-11 11:16am    
that event does not get fired.
Thanks
You will need to set up a KeyPress event handler for each cell.
So - handle the DGV EditingControlShowing event. Within the handler, filter for the cells you are interested in and, for those cells, add a new KeyPressEventHandler.
e.g.
C#
public class MyDgv : DataGridView
{
    protected override void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e)
	{
		base.OnEditingControlShowing(e);

		// Set up handler for cells in column 0 only
		if (this.CurrentCell.ColumnIndex == 0)
		{
			// Remove handler before adding, to prevent accumulation of handlers
			e.Control.KeyPress -= new KeyPressEventHandler(MyDgv_OnKeyPress);
			e.Control.KeyPress += new KeyPressEventHandler(MyDgv_OnKeyPress);
		}
	}

	private void MyDgv_OnKeyPress(object sender, KeyPressEventArgs e)
	{
		if (e.KeyChar == 't')
		{
			// Multiply cell contents by 1000
			int val = int.Parse(((DataGridViewTextBoxEditingControl)sender).Text) * 1000;
			// Update cell
			((DataGridViewTextBoxEditingControl) sender).Text = val.ToString();
			// Prevent new character ('t') from being entered in the cell
			e.Handled = true;
		}
	}
} 


I'm sure there are other ways, but this works for me.
 
Share this answer
 
Comments
arkiboys 28-Sep-11 3:24am    
Hi, Is there a way to place the keypress event on only one column of the datagridview control?
Thanks
Zasky 6-Oct-11 5:42am    
Yes, the code above only handles the KeyPress on column 0.
// you can define cell value format like this

C#
grd_dtls.Columns["grd_txt_qty"].DefaultCellStyle.Format = "N2";
             grd_dtls.Columns["grd_txt_qty"].ValueType = typeof(System.Double);



and for cell Value change calculation you have to for

C#
private void grd_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

// write your code here

}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900