Crazyd22 Crazyd22 - 12 days ago 4
C# Question

Simulate button click c#

Hey, I am trying to make a simulation of a button click for a password form, basically the form1 loads and shows form2 as a dialogue, and if it does not give back DialogResult.OK, then it closes the application.

So far I have in the button:

if (txtpass.Text == "")
{
MessageBox.Show("You need to enter a password", "Password", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
txtpass.Focus();
}
else
{
if (txtpass.Text == "1234")
{
radButton1.DialogResult = DialogResult.OK;
radButton1.PerformClick();
}
else
{
MessageBox.Show("Password Incorrect", "Password", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtpass.Text = "";
txtpass.Focus();
}
}


So far as you can see I am trying to use
radButton1.PerformClick();
but that gives me the error message:

An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll


Any ideas?

Thanks.

Answer

Edit Not a guess. Telling the button to click itself from within itself is most definitely causing an infinite loop. This causes the method to get called over and over, filling up the stack and causing it to overflow.

My guess is that calling PerformClick() is causing the current method you posted to get called again, thus causing an infinite call loop and resulting in a StackOverflowException.

To prevent this, you need to fix the logic somewhere in your code so that:

if (txtpass.Text == "1234")

evaluates to false and the click method doesn't get called over and over. You can probably achieve this by setting txtpass.Text = "" right before you cause it to click itself again.

Comments