我有一个自动绑定的DataGridView,它直接从
Strongly Typed Dataset
及其
TableAdapter
.
这个
DataGridView
允许数据编辑,但我在处理格式错误的数据输入时遇到问题。
例如,其中一列是日期,在数据库中格式化为
datetime
,11/05/2010。您可以编辑日期和
数据表格控件
打开一个
TextBox
您可以在其中输入字母、Simbols和其他未经授权的字符。当您完成编辑单元格时,如果有如此糟糕的数据,它将引发
System.FormatException
如何阻止输入某些数据?
在将数据发送回DataGridView之前,是否有方法“过滤”该数据?
======================================================
正如艾伦所说,关键是处理细胞验证事件。我将附加一些有助于处理值的代码:
public static void CellValidating(object sender, System.Windows.Forms.DataGridViewCellValidatingEventArgs e)
{
string newValue = e.FormattedValue.ToString();
string oldValue = ((System.Windows.Forms.DataGridView)(sender)).Rows[e.RowIndex].Cells[e.ColumnIndex].FormattedValue.ToString();
//i like to check that the value has changed before validating it
if (newValue != oldValue)
{
if (false)//replace this with actual validation.
{
//if data not valid cancel validation
e.Cancel= true;
}
}
}