Warm tip: This article is reproduced from stackoverflow.com, please click
c# winforms datagridview

DataGridView CellValidated Event triggers when closing form

发布于 2020-03-27 10:22:27

Situation: I have placed a DataGridView on a form. In the DataGridView-Object I do checks on some cells - like for example if the amount which was entered by the user is not greater than 100. The checks will be performed when the user leaves the cell with Enter, Tab or the Arrow Keys.

Problem: Everything is working fine but when the cursor is in the cell and the value is greater than 100 and the User presses the "X"-Button on the form (Close-Button) the Message still appears.

Question: How can I prevent the appearance of the MessageBox when the User is clicking on the X-Button on the form?

Code Samples:

private void dgv_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                const int nColumn = 2;
                if (!e.ColumnIndex.Equals(nColumn))
                {
                    return;
                }

                if (e.ColumnIndex.Equals(nColumn))
                {
                    double nMengeSource;
                    double.TryParse(dgv.Rows[e.RowIndex].Cells[fldMenge.Name].Value.ToString(),
                        out nMengeSource);

                    double nMengeLos;
                    double.TryParse(dgv.Rows[e.RowIndex].Cells[fldMengeLos.Name].Value.ToString(),
                        out nMengeLos);

                    // prüfe ob erfasste Menge die Menge im Los überschreitet
                    if (nMengeSource > nMengeLos)
                    {
                        var sMsg = String.Empty;
                        sMsg += "Warning! Value is greather than allowed!";
                        MessageBox.Show(sMsg, "Check...", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                Dialog.SetDefaultCursor();
                MessageBox.Show(MethodBase.GetCurrentMethod().Name + @"\n\n" + ex + @"\n\n" + ex.Message);
            }
        }
Questioner
HNITC
Viewed
39
OhBeWise 2015-05-21 01:57

By clicking X, the DataGridViewCell loses focus, which causes the validation on the cell to fire. You want to suppress this, but only when the Form is closing. However, you can't do this in Form.FormClosing because it is fired after validation has occurred. But you can do it with the following method:

protected override void WndProc(ref Message m)
{
  switch (((m.WParam.ToInt64() & 0xffff) & 0xfff0))
  {
    case 0xf060:
      this.dataGridView1.CausesValidation = false;
      break;
  }

  base.WndProc(ref m);
}