0

I have UI form in C# with a bunch of combo boxes and a text box. I have the validated and validating events associated with the text box to make sure the user selects valid input. I also have a "View Results" and "Export Results" buttons in the form. When I click on any of the two buttons, it surely validates the text box input but doesn't do the action that the button is supposed to do. I am having to click the button again to trigger the action that the button is supposed to do.

What should I do so that the button click event does both validation and also action it is intended to do?

Here is excerpt from my code

private void NameTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
 {
     if (!isValidName())
     {
         e.Cancel = true;
         NameTextBox.Select(0,NameTextBox.Length);
         InvalidPMLabel.Visible = true;
         InvalidPMLabel.Text = "Invalid Name";
         ExportButton.Enabled = false;
         ViewResultsButton.Enabled = false;
         GroupTextBox.Clear();
    }
 }  



private void NameTextBox_Validated(object sender, EventArgs e)
{
    string combination = null;
    int index = -1;
    sql = "select .......";
    dSet = get_data(sql);
    MaxRows = dSet.Tables[0].Rows.Count;
    if (MaxRows != 0)  
    {
        dSet.Clear();
        ...
        ...
    }
    else
    {
        ...
        ...
        ...
    }
    GroupTextBox.Text = dSet.Tables[0].Rows[index]["group"].ToString(); 
}

private void ViewResultsButton_Click(object sender, EventArgs e)
{
    view_marks();
    view_grade();
}
let_there_be_light
  • 837
  • 3
  • 9
  • 15

2 Answers2

0

I think that when your code execute the line e.Cancel = true; it prevents the button event to continue. Try removing this part and see if the event is performed after the validation.

Vyrira
  • 174
  • 8
0

So I've noticed that you are using events to do your validations. You have 2 options. You can call these validations events inside your onclick event or use a method for your validation and call that method. I am a fan of the method route so i will be showing that

private bool Validated()
{
    bool check;
    //do all your code and set a value for check

    return check;

}


private void ViewResultsButton_Click(object sender, EventArgs e)
{
   if(Validated() == true)
    {

    view_marks();
    view_grade();
    }
}

The other route is doing the same with events, but I have not done it before.

solafidei
  • 11
  • 1