DataGridView.CellValidating 事件,確定使用者只輸入正整數。

  • 13968
  • 0

DataGridView.CellValidating 事件,確定使用者只輸入正整數。

下列程式碼範例會處理 CellValidating 事件,確定使用者只輸入正整數。

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";
    }
}

Ref:msdn.microsoft.com/zh-tw/library/system.windows.forms.datagridview.cellvalidating(VS.80).aspx