.net: How To Prevent users from continuing to work with a winform when data he entered is not valid?

63 views Asked by At

hi I have a winform which has several controls like datagridviewes, textboxes, listboxes and so on. The senario is that when a user enters a code in textbox1, system checkes for its validation and then automatically retrieves its related data from database and finally the user can save all the data into database.

But if the data user has entered is not valid, I think it's better to display a message to user and prevent him from continuing to enter other data.

Is this possible by using events? Or you suggest a better solution? Actually is there any best practice for such these senarios?

Thanks in advance

1

There are 1 answers

0
JPReddy On

I hope I understood your problem correctly.

You have several controls in the form and you are entering a particular code in the textbox and if that code is correct it will fetch some data from database and if that code is incorrect warn the user for invalid code and set the focus back to the textbox.

You can do the following for the same.

private void CodeTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
  if(CodeIsValid())
  {
    // do your database work here
  }
  else
  {
    MessageBox.Show("Invalid code, please enter correct code");
    e.Cancel = true;
  }
}

private bool CodeIsValid()
{
  // Validate code here
}