2012-08-04 82 views
1

我有的DataGridView输入验证一些严重的问题:如何验证DataGridView输入?

我的工作与实体框架的一个项目,我已经绑定一个的DataGridView元素的数据库。

如果用户将某些数据插入到不可空列中,并在清除数据后将列留空,然后单击另一个单元格,则会发生异常,并且出现运行时错误。

或者,如果用户试图将字符串插入到整数列中,它们会得到非常长的错误消息,根本不是用户友好的。

是否有任何简单的方法来验证DataGridView单元?

回答

2

我相信你正在寻找DataGridView.DataError事件。如果您想对数据进行自定义验证,则应该处理此事件。如下所示:

private void Form1_Load(object sender, EventArgs e) 
    { 
     dataGridView1.DataSource = entities; 
     dataGridView1.DataError += new DataGridViewDataErrorEventHandler(dataGridView1_DataError); 
    } 

    void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e) 
    { 
     // you can obtain current editing value like this: 
     string value = null; 
     var ctl = dataGridView1.EditingControl as DataGridViewTextBoxEditingControl; 

     if (ctl != null) 
      value = ctl.Text; 

     // you can obtain the current commited value 
     object current = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; 
     string message; 
     switch (e.ColumnIndex) 
     { 
      case 0: 
       // bound to integer field 
       message = "the value should be a number"; 
       break; 
      case 1: 
       // bound to date time field 
       message = "the value should be in date time format yyyy/MM/dd hh:mm:ss"; 
       break; 
      // other columns 
      default: 
       message = "Invalid data"; 
       break; 
     } 

     MessageBox.Show(message); 
    } 

您可以检查输入数据的值并显示该值的相应错误消息。例如,如果值为空或空且该字段不可为空,则可以显示一条消息,指示该值不能为空。

希望这会有所帮助。

+0

谢谢,不工作的时候,你必然'DataGridView'到'实体FrameWork' – 2012-08-13 14:12:00

+0

@masoudkeshavarz我已经与实体框架4.0测试,它为我工作。我觉得你的情况是不同的,你能解释一下你正在做什么,就像你如何为gridview的数据源,你在运行时改变其列类型不进入'DataError'事件。 – Ashkan 2012-08-13 17:15:37

+0

谢谢你的回复。我以前曾试图用'DataError'处理这个异常。但是当你使用Entity FrameWork时''DataError'事件永远不会发生。当你留下一个空字段的字段时,会出现其他地方发生的异常,并出现以下消息:“该属性不能设置为空值”。我通过以下步骤提供了“数据源”。我制作了一个'edmx'文件。我把我的桌子拖进去了。我在'Data Source'选项卡中点击'Add New Data Source'并选择'Object'提供的d数据。然后我绑定了我的'DataGridView'。 – 2012-08-14 06:58:47

0

将下面的代码用于处理DataError事件:

switch (e.ColumnIndex) 
     { 
      case 0: 
       // bound to integer field 
       message = "the value should be a number"; 
       break; 
      case 1: 
       // bound to date time field 
       message = "the value should be in date time format yyyy/MM/dd hh:mm:ss"; 
       break; 
      // other columns 
      default: 
       message = "Invalid data"; 
       break; 
     } 

     MessageBox.Show(message);