如何validationDataGridView输入?
我对DataGridView输入validation有一些严重的问题:
我正在使用Entity Framework开发一个项目,并且我已将DataGridView元素绑定到数据库。
如果用户将一些数据插入到不可为空的列中,然后清除数据以使列保持空白,则单击另一个DataGridView单元格,发生exception并且我收到运行时错误。
或者,如果用户尝试将字符串插入到整数列中,则会得到一条非常长的错误消息,该消息根本不是用户友好的。
是否有任何简单的方法来validationDataGridView单元格?
我相信你正在寻找DataGridView.DataError
事件。 如果要对数据进行自定义validation,则应该处理此事件。 像这样的东西:
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); }
您可以检查输入数据的值并显示该值的相应错误消息。 例如,如果value为null或为空并且该字段不可为空,则可以显示一条消息,指示该值不能为空。
希望这可以帮助。
将以下代码用于处理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);