我有一些严重的问题数据网格视图输入验证:
我正在使用实体框架开发一个项目,并且我已经绑定了数据网格视图元素到数据库。
如果用户将一些数据插入到不可为空的列中,然后清除数据以使该列留空,然后单击另一个数据网格视图单元格时,发生异常并且出现运行时错误。
或者,如果用户尝试将字符串插入整数列,他们会收到一条非常长的错误消息,这对用户来说根本不友好。
有什么简单的方法可以验证吗数据网格视图 cells?
我相信你正在寻找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);
}
您可以检查输入数据的值并显示该值的相应错误消息。例如,如果值为 null 或为空且该字段不可为空,则可以显示一条消息,指示该值不能为空。
希望这可以帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)