DataGridView.CellValidating 事件
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
在单元格失去输入焦点时发生,并启用内容验证功能。
public:
event System::Windows::Forms::DataGridViewCellValidatingEventHandler ^ CellValidating;
public event System.Windows.Forms.DataGridViewCellValidatingEventHandler CellValidating;
public event System.Windows.Forms.DataGridViewCellValidatingEventHandler? CellValidating;
member this.CellValidating : System.Windows.Forms.DataGridViewCellValidatingEventHandler
Public Custom Event CellValidating As DataGridViewCellValidatingEventHandler
事件类型
示例
下面的代码示例处理 CellValidating 事件,以确保用户只输入正整数。 此示例是参考主题中提供的更大示例的 VirtualMode 一部分。
void VirtualConnector::dataGridView1_CellValidating
(Object^ sender, DataGridViewCellValidatingEventArgs^ e)
{
int newInteger;
// Don't try to validate the 'new row' until finished
// editing since there
// is not any point in validating its initial value.
if (dataGridView1->Rows[e->RowIndex]->IsNewRow)
{
return;
}
if (!Int32::TryParse(e->FormattedValue->ToString(),
newInteger) || (newInteger < 0))
{
e->Cancel = true;
}
}
private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
dataGridView1.Rows[e.RowIndex].ErrorText = "";
int newInteger;
// Don't try to validate the 'new row' until finished
// editing since there
// is not any point in validating its initial value.
if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; }
if (!int.TryParse(e.FormattedValue.ToString(),
out newInteger) || newInteger < 0)
{
e.Cancel = true;
dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be a non-negative integer";
}
}
Private Sub dataGridView1_CellValidating(ByVal sender As Object, _
ByVal e _
As DataGridViewCellValidatingEventArgs) _
Handles dataGridView1.CellValidating
Me.dataGridView1.Rows(e.RowIndex).ErrorText = ""
Dim newInteger As Integer
' Don't try to validate the 'new row' until finished
' editing since there
' is not any point in validating its initial value.
If dataGridView1.Rows(e.RowIndex).IsNewRow Then Return
If Not Integer.TryParse(e.FormattedValue.ToString(), newInteger) _
OrElse newInteger < 0 Then
e.Cancel = True
Me.dataGridView1.Rows(e.RowIndex).ErrorText = "the value must be a non-negative integer"
End If
End Sub
注解
取消此事件将取消对当前单元格所做的更改。 在数据绑定模式下取消此事件时,不会将新值推送到基础数据源。 在虚拟模式下取消此事件时,不会引发该 CellValuePushed 事件。
CellValidated处理 事件以执行验证后处理。
有关如何处理事件的详细信息,请参阅 处理和引发事件。