mattc19
mattc19

Reputation: 718

firing button_click event with code and returning DialogResult.OK

I would like to fire a button click event if the user presses enter on a text box but when I do the button is not returning a DialogResult.OK. When I physically click the button it works though. Any ideas?

Here is my parent form code

using (var completedForm = new CompletedForm(Qty))
{
    DialogResult result = completedForm.ShowDialog();
    if (result == DialogResult.OK)
    {
        return completedForm.QtyCompleted;
    }
    MessageBox.Show("Invalid Qty, Please Try Again");
  return 0;  
}

Here is my child form button click event

private void btnPartialComplete_Click(object sender, EventArgs e)
{
    if(tbQtyComplete.Text == "")
    {
        tbQtyComplete.Text = "0";
    }

    this.QtyCompleted = int.Parse(tbQtyComplete.Text);
    this.Close();
}

And here is my textbox keydown event

private void tbQtyComplete_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyCode == Keys.Return)
    {
        btnPartialComplete_Click(null, EventArgs.Empty);
    }
}

Any ideas why the textbox event wouldn't cause the button to return a DialogResult.OK?

Upvotes: 1

Views: 723

Answers (1)

Hamid Pourjam
Hamid Pourjam

Reputation: 20754

You should use btnPartialComplete.PerformClick(). By calling PerformClick() you are generating a click event for your button but when you call btnPartialComplete_Click you just executing a function which is registered to be executed when click event of the button is raised. So calling btnPartialComplete_Click is not equal to clicking the button.

Upvotes: 1

Related Questions