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處理 事件以執行驗證後處理。
如需如何處理事件的詳細資訊,請參閱 處理和引發事件。