我有一个表单,如果用户在文本框中键入隐藏问题的正确答案,它将转到数据库中下一个随机选择的记录,并在数据库的player表中的playerscore列添加+1。但是,分数不会在数据库或标签中更新。
我已经删除了这篇文章中的所有其他代码,例如连接字符串,但它就在那里并且正在建立连接。
private void SubmitAnswer_Click(object sender, EventArgs e)
{
int score = 0;
if (WordBox.Text == WordLbl.Text)
{
TopLbl.Text = "Well done! :)";
synthesizer.SpeakAsync("Well done. Now try answering this...");
this.BackColor = System.Drawing.Color.OliveDrab;
String command = "SELECT TOP 1 * FROM Questions ORDER BY Rnd(-(100000*ID)*Time())";
try
{
FillDataTable(command);
ShowRow(currentRow);
score++; // Adding one each time the player spells the word correctly.
ScoreLabel.Text = "Score: " + score.ToString(); // Update the label to display new score.
myAdapter.SelectCommand.CommandText = "UPDATE Questions SET players = playerscore + 1 WHERE ID =" + currentRow;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
synthesizer.SpeakAsync("Answer the question" + WordLbl.Text);
}
else
{
TopLbl.Text = "Try answering this question again";
synthesizer.SpeakAsync("Try answering this question again");
this.BackColor = System.Drawing.Color.Red; color on the form.
}
}
我怀疑这可能低至currentRow
。在该计划的顶部:
// Index of the current record
private int currentRow = 0;
ShowRow类
private void DisplayRow(int rowIndex)
{
if (myDataTable.Rows.Count == 0)
return;
if (rowIndex >= myDataTable.Rows.Count)
return;
try
{
DataRow row = myDataTable.Rows[rowIndex];
KS1WordLbl.Text = row["Word"].ToString();
synthesizer.SpeakAsync("Answer the question" + WordLbl.Text);
}
catch (Exception ex)
{
MessageBox.Show("Error in DisplayRow : \r\n" + ex.Message);
}
}
答案 0 :(得分:1)
假设FillDataTable填充myDataTable
及其范围,您应该能够将where子句更新为
where id = " + myDataTable.Rows[0].[id].ToString()
您当前正在尝试做的更像是就地更新,您需要做的是提取记录ID并使用它来告诉db要更新哪条记录
请注意,虽然您不必担心SQL注入攻击,因为ID不受用户控制,您应该查看参数化查询。