datagridview单元格格式 [英] datagridview cell format

查看:98
本文介绍了datagridview单元格格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在winform的datagridview的单元格中键入一个值时,我想检查输入的值.
例如,在datagridview的一个单元格中,我输入3,然后输入m
我基本上想看看用户是否输入了m或t,如果是,则分别将数字乘以1000000或1000.
是否有事件要检查是否将文本输入到单元格中?
谢谢

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

推荐答案

您可以使用KeyDown事件在用户输入字符时通读输入的字符.
可以通过本文所述的一些操作来完成:
http://social.msdn.microsoft.com/Forums/zh_cn/winformsdatacontrols/thread/db486d50-48f3-405d-bc7a-ad3720d4dd57 [
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[^]


您需要为每个单元格设置KeyPress事件处理程序.
因此-处理DGV EditingControlShowing事件.在处理程序中,过滤您感兴趣的单元格,并为这些单元格添加一个新的KeyPressEventHandler.
例如
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.
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.


//您可以定义像这样的单元格值格式

// you can define cell value format like this

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

private void grd_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {


//在这里编写您的代码

}


// write your code here

}


这篇关于datagridview单元格格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆