简体   繁体   中英

C# radiobutton keydown event

I have made a simple code that will accept (enter key) the selected radiobutton. And check the radiobutton text if it matches with the answer. But this code is too redundant, is there a way to make it simpler?

private void btn1_KeyDown(object sender, KeyEventArgs e)
{
    var row = dTable.Rows[currentRow];
    var ans = row["ANSWER"].ToString();
    if (btn1.Text == ans)
    {
    scoreAdd();
    MessageBox.Show("Correct");
    }
    else
    {
    MessageBox.Show(ans);
    }
    currentRow++;
    nextRow();
}

private void btn3_KeyDown(object sender, KeyEventArgs e)
{
    var row = dTable.Rows[currentRow];
    var ans = row["ANSWER"].ToString();
    if (btn3.Text == ans)
    {
        scoreAdd();
        MessageBox.Show("Correct");
    }
    else
    {
            MessageBox.Show(ans);
    }
    currentRow++;
    nextRow();
}

private void btn4_KeyDown(object sender, KeyEventArgs e)
{
    var row = dTable.Rows[currentRow];
    var ans = row["ANSWER"].ToString();
    if (btn4.Text == ans)
    {
        scoreAdd();
        MessageBox.Show("Correct");
    }
    else
    {
            MessageBox.Show(ans);
    }
    currentRow++;
    nextRow();
}
private void button_KeyDown(object sender, KeyEventArgs e)
{
  Button button = sender as Button;

  var row = dTable.Rows[currentRow];
  var ans = row["ANSWER"].ToString();
  if (button.Text == ans)
  {
      scoreAdd();
      MessageBox.Show("Correct");
  }
  else
  {
      MessageBox.Show(ans);
  }
  currentRow++;
  nextRow();
}

Just cast sender as Button and get Text from it.

And bind all event buttons to button_KeyDown.

This way you have only 1 method.

Create a general method for the logic like:

protected void TheLogic(string txt)
{
   var row = dTable.Rows[currentRow];
    var ans = row["ANSWER"].ToString();
    if (txt == ans)
    {
    scoreAdd();
    MessageBox.Show("Correct");
    }
    else
    {
    MessageBox.Show(ans);
    }
    currentRow++;
    nextRow();
}

Then call the TheLogic function in each KeyDown event using the corresponding parameter text, eg,

private void btn3_KeyDown(object sender, KeyEventArgs e)
{
    TheLogic(btn3.Text);
}

private void btn4_KeyDown(object sender, KeyEventArgs e)
{
    TheLogic(btn4.Text);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM