积极答复者
DataGridView数据验证问题

问题
答案
-
自己搞定了, 在CellValidating中判断
//如果没有未提交更改,就不验证数据
if(!IsCurrentCellDirty)
{
return;
}在RowValidating中判断
if (!IsCurrentRowDirty)
{
return;
}- 已标记为答案 ThankfulHeartModerator 2013年11月8日 12:08
全部回复
-
-
虾舞天涯:
就我所知道的,CellValidating只有在你修改单元格内容后焦点离开单元格(在数据被数据源等接受前)才会触发。这就意味着您输入的每个内容必须是合法的方可被接受。您现在不是这个问题吗?可以列出你的代码或者干脆上传代码让我们看看吗?谢谢您了。
http://msdn.microsoft.com/zh-cn/library/system.windows.forms.datagridview.cellvalidating(v=VS.80).aspx:关于CellValidating的介绍。
For Account Validation, please follow "Verify Account+Number" at http://social.msdn.microsoft.com/Forums/en-us/home?forum=reportabug
For ASP.NET Question, please ask at http://forums.asp.net
For other questions, you can find a specific forum and then ask at http://stackexchange.com/sites
Click and Donate at http://www.freerice.com -
只要离开单元格 不管单元格里面的数据有没有被修改, CellValidating都会触发, 这样触发也太频繁了
一般只要用户对单元格修改之后,就在CellValidating中验证, 如果验证失败就 e.Cancel = true;
但是用户没有修改单元格, CellValidating也会触发, 我现在的做法是在CellValidating的时候主动判断单
元格里面的内容有没有变,如果没有变就return,但是每个Grid都这样判断,那也太多重复的工作了
希望只有当单元格内的数据修改之后才触发, 谢谢
- 已编辑 虾舞天涯 2013年11月8日 2:28
-
CellValidating可能必须在焦点离开时候验证,看来不怎么合适你用。
我建议:
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { //现在输入的数据 string currentvalue = e.FormattedValue.ToString(); //原有的数据 string originalvalue = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString(); //如果现在数据和原有数据一样,没有发生变化,不做验证 if(!dataGridView1.Rows[e.RowIndex].IsNewRow && (currentvalue!=originalvalue)) { int vnum = 0; if (!int.TryParse(, out vnum)) { e.Cancel = true; MessageBox.Show("数据出错!"); } } } private void Form1_Load(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Columns.Add("Id", typeof(string)); for (int i = 1; i < 6; i++) { dt.Rows.Add(i); } dataGridView1.DataSource = dt; } }
For Account Validation, please follow "Verify Account+Number" at http://social.msdn.microsoft.com/Forums/en-us/home?forum=reportabug
For ASP.NET Question, please ask at http://forums.asp.net
For other questions, you can find a specific forum and then ask at http://stackexchange.com/sites
Click and Donate at http://www.freerice.com -
自己搞定了, 在CellValidating中判断
//如果没有未提交更改,就不验证数据
if(!IsCurrentCellDirty)
{
return;
}在RowValidating中判断
if (!IsCurrentRowDirty)
{
return;
}- 已标记为答案 ThankfulHeartModerator 2013年11月8日 12:08
-
谢谢您提供了宝贵的答案,欢迎您再来!
For Account Validation, please follow "Verify Account+Number" at http://social.msdn.microsoft.com/Forums/en-us/home?forum=reportabug
For ASP.NET Question, please ask at http://forums.asp.net
For other questions, you can find a specific forum and then ask at http://stackexchange.com/sites
Click and Donate at http://www.freerice.com