Hey so I have the following code which should throw up the errors if the text boxes are empty but it doesn’t it just carries on with what it would do were they not and adds an item with 0 or whatever to the list instead, is there a problem with my code?
private void BtnAdd_Click(object sender, EventArgs e)
{
try
{
theVisit.name = txtName.Text;
theVisit.address = txtAddress.Text;
theVisit.arrival = DateTime.Parse(txtArrival.Text);
//Update theVisit object to reflect any changes made by the user
this.Hide();
//Hide the form
}
catch (Exception)
{
if (txtName.Text == "")
MessageBox.Show("please enter a customer name");
if(txtAddress.Text == "")
MessageBox.Show("Please enter a customer address");
if(txtArrival.Text == "")
MessageBox.Show("Please enter an arrival time");
}
NEW
if (txtName.Text == "" || txtAddress.Text == "" || txtArrival.Text == "")
MessageBox.Show(" Please enter a value into all boxes");
else
theVisit.name = txtName.Text;
theVisit.address = txtAddress.Text;
theVisit.arrival = DateTime.Parse(txtArrival.Text);
//Update theVisit object to reflect any changes made by the user
The try-catch-statement is used to catch and handle exceptions. An exception can be thrown, if an index is out of bounds, if members of a variable set to null are accessed, and in many other situations. A
TextBoxbeing empty is not an error by itself and does not throw an exception.I suggest you to use a completely different approach. Add an
ErrorProviderto your form. You find it in the toolbox in the section “Components”. Now you can add the following code to your form:Select the
ValidateTextBoxmethod as error handler for theTextChangedevent of all your textboxes. Insert the desired message in theTagproperty of the textboxes. Set theBlinkStyleproperty of theErrorProvidertoErrorBlinkStyle.NeverBlink. You can do these settings in code or in the form designer.Now a red error symbol will appear next to empty textboxes. If you hoover the mouse over them, a tooltip with the error message will appear.
UPDATE
I updated the code above to automatically disable or enable the “Add”-button. Therefore I added a
HashSetthat contains all the controls currently being in an error state. If the set is empty the button is enabled, otherwise disabled.