70-511 Exam Prep: Validating Data in the Windows Forms DataGridView Control

So the question might be: The application requires that a certain value, for instance, 10, needs to be entered into a cell, if the condition is not met, then the user must receive feedback, perhaps an electric shock through an appropriate USB device and an error message.  How would you validate the data?  (Ok, you wouldn’t use an electric shock, maybe a strobe light?).

There are two ways:

CellValidating:

Occurs when a cell loses input focus, enabling content validation

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)

               {

                    //Send message to strobe light or visual feedback

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

ErrorProvider:
    • Use a Windows Forms ErrorProvider component to display an error icon when the user enters invalid data
    • Requires at least two controls on the form in order to tab between them and thereby invoke the validation code

 

protected void textBox1_Validating (object sender, System.ComponentModel.CancelEventArgs e)

{

        try

        {

           

             int x = Int32.Parse(textBox1.Text);

             errorProvider1.SetError(textBox1, "");

         }

        catch (Exception ex)

        {

             errorProvider1.SetError(textBox1, "Not an integer value.");

         }

}