Reputation: 31
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();
}
Upvotes: 0
Views: 412
Reputation: 699
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, e.g.,
private void btn3_KeyDown(object sender, KeyEventArgs e)
{
TheLogic(btn3.Text);
}
private void btn4_KeyDown(object sender, KeyEventArgs e)
{
TheLogic(btn4.Text);
}
Upvotes: 1
Reputation: 316
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.
Upvotes: 1