如何防止在 DataGridViewCell 中输入格式错误的数据
我有一个自动绑定的 DataGridView,它直接从强类型数据集
及其TableAdapter
获取数据和更新数据。
DataGridView
允许数据编辑,但我在处理格式错误的数据输入时遇到问题。
例如,其中一列是日期,在数据库中格式为 datetime
, 11/05/2010。您可以编辑日期,DataGridView
将打开一个 TextBox
,您可以在其中输入字母、符号和其他未经授权的字符。当您完成编辑单元格时,如果有如此错误的数据,它会抛出 System.FormatException
如何阻止输入某些数据?
有没有办法在数据发送回 DataGridView 之前“过滤”该数据?
=================================================== =======================
正如Alan所说,关键是处理cellValidating事件。我将附加一些有助于处理该值的代码:
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;
}
}
}
I have an automatically binded DataGridView that obtains data and update data directly from a Strongly Typed Dataset
and its TableAdapter
.
the DataGridView
allows data editing but I'm having issues dealing with bad formatted data input.
For example, one of the columns is a date, formatted in the database as datetime
, 11/05/2010. You can edit the date and the DataGridView
opens a TextBox
in which you can enter letters, simbols and other unauthorised characters. When you finish editing the cell if has such bad data it throws a System.FormatException
How can I prevent some data to be entered?
Is there a way to "filter" that data before it is sent back to the DataGridView?
=========================================================================
As Alan said, the key was to handle the cellValidating event. I'll attach some code that helps to handle the value:
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;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
DataGridView 上有 Row/CellValidating 事件,您可以使用这些事件来验证输入并在输入无效时取消事件 - 这会使行/单元格处于编辑模式。
There are Row/CellValidating events on the DataGridView, you can use these to validate input and cancel the event if input is invalid - this leaves the row/cell in edit mode.