KansaiRobot
KansaiRobot

Reputation: 9912

Can not validate a cell in DataGridView

I have been programming a winform application and in one form I have a dataGridView. A particular column is made of integers so the DataTable that is the source of the grid got defined as this

  DataTable dt = new DataTable();
  dt.Columns.Add("Partition", typeof(int));
  dt.Columns.Add("Number", typeof(int));

Anyway, later I try to validate this in order that the user does not introduce for example "dadada".

So I do

 private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{int result;
  if (!(int.TryParse(e.FormattedValue.ToString(), out result))) 
      {Trace.Writeline("error");
      return;
      }
}

TryParse is supposed to not throw an exception, and it handles it well until the last } when going out of the function it thows an exception.

I tried

 private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {

            int result=0;
            try
            {

                result = int.Parse(e.FormattedValue.ToString());
            }
            catch
            {
                MessageBox.Show("error");
                dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
                return;
            }
            if(result<0)
            {
                MessageBox.Show("positives!");
                return;
            }

        }

And this time the catch catches the exception (of Parse) but then after that again another exception is produced while leaving the function.

I wonder what is wrong and how to validate the integer entrance of the grid

Upvotes: 0

Views: 66

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460048

You have to set Cancel to true:

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    dataGridView1.Rows[e.RowIndex].ErrorText = "";
    int result;

    // 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 result))
    {
        e.Cancel = true;
        dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be an integer";
    }
    else if(result < 0)
    {
        e.Cancel = true;
        dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be positive";
    }
}

MSDN shows a good example.

Upvotes: 1

Related Questions