简体   繁体   English

C#单选按钮按下事件

[英]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. 只需将发件人转换为Button并从中获取文本。

And bind all event buttons to button_KeyDown. 并将所有事件按钮绑定到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, 然后,使用相应的参数文本在每个KeyDown事件中调用TheLogic函数,例如,

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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