Note that there are some explanatory texts on larger screens.

plurals
  1. POCall button click event on pressing Enter - c#
    primarykey
    data
    text
    <p>I am new to c# - I want to trigger button click event on pressing enter. My code not working properly - </p> <p>issue is that when i press enter on submitting some value, it displays messagebox which it should show but on pressing Enter for OK button of Messagebox, it automatically triggers button click event again even i don't press enter or enter any other value. </p> <pre><code>public partial class Form1 : Form { int n1, n2 = 0; private static readonly Random getrandom = new Random(); private static readonly object syncLock = new object(); public int GetRandomNumber(int min, int max) { lock (syncLock) { // synchronize return getrandom.Next(min, max); } } public int tQuestion() { n1 = GetRandomNumber(2, 11); n2 = GetRandomNumber(2, 11); string tQues = n1 + " x " + n2 + " = "; label1.Text = tQues; return 0; } public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { tQuestion(); } private void label1_Click(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { textBox1.KeyDown += new KeyEventHandler(tb_KeyDown); } public void button1_Click(object sender, EventArgs e) { string tAns = textBox1.Text; int answer = n1 * n2; string tOrgAns = answer.ToString(); if (tAns == tOrgAns) MessageBox.Show("Your answer is Corect", "Result", MessageBoxButtons.OK,MessageBoxIcon.Exclamation ); else MessageBox.Show("Your answer is WRONG", "Result", MessageBoxButtons.OK, MessageBoxIcon.Stop); textBox1.Text = ""; textBox1.Focus(); tQuestion(); } static void tb_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { button1_Click(sender, e); } } </code></pre> <p>Moreover, code only works if i remove <code>static</code> from <code>static void tb_KeyDown(object sender, KeyEventArgs e)</code> - otherwise it gives error: </p> <blockquote> <p>An object reference is required for the non-static field, method, or property</p> </blockquote> <p>Please help me - i am new to c# &amp; .Net</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload