在我的Visual Studio项目中,我通过foreach语句为表(MySQL)上的每个记录创建一个按钮,每个按钮都是通过以下方法创建的:
void createRewardButton(int y, int rewardsAmount, string rewardName, int value)
{
int x = 200;
//Create Button object
Button rewardButton = new Button();
///Set button properties
rewardButton.Name = "button"+rewardName;
rewardButton.Height = 60;
rewardButton.Width = 400;
rewardButton.Location = new Point(x,y);
rewardButton.Text = "You won "+ rewardsAmount + " awards for " + rewardName + ". Value: " + value + " tokens";
rewardButton.BackColor = Color.WhiteSmoke;
rewardButton.FlatStyle = FlatStyle.Flat;
//Add button to Awards Panel
panel_Rewards.Controls.Add(rewardButton);
///Button event handlers
rewardButton.MouseHover += new EventHandler(rewardButton_MouseEnter);
rewardButton.MouseLeave += new EventHandler(rewardButton_MouseLeave);
///Event handler for the click method
rewardButton.Click += new EventHandler((sender, e) => rewardButton_Click(sender, e, value));
//Button controls
void rewardButton_MouseEnter(object sender, EventArgs e)
{
rewardButton.BackColor = Color.FromArgb(100, Color.Gray); ;
}
void rewardButton_MouseLeave(object sender, EventArgs e)
{
rewardButton.BackColor = Color.WhiteSmoke;
}
// On click control method
void rewardButton_Click(object sender, EventArgs e, int rValue)
{
increaseTokens(rValue);
}
}
我希望每个按钮在每次单击时都执行递增令牌()方法,该方法需要一个int参数。我发现我可以对事件处理程序使用lambda语法,以在奖励Button_click事件上使用“值”作为参数。
这是递增令牌方法的代码:
void increaseTokens(int value)
{
////Connection String//////////
string connStr = "SERVER=localhost;" + "DATABASE=scores;" + "UID=root;" + "PASSWORD=password;";
//Connection object
MySqlConnection dbcon = new MySqlConnection(connStr);
try
{
dbcon.Open();
}
catch (Exception err)
{
MessageBox.Show("Message: " + err.Message);
}
if (dbcon.State == ConnectionState.Open)
{
String query = "UPDATE agents SET agentTokens = @value WHERE agentEid = @EID";
//Create Command
MySqlCommand cmd = new MySqlCommand(query, dbcon);
cmd.Parameters.AddWithValue("EID", EID);
cmd.Parameters.AddWithValue("value", value);
cmd.ExecuteNonQuery();
}
}
已创建按钮,但是单击按钮时未更新数据库。由于我没有收到任何错误或警报,所以我不知道rewardButton_click事件是否接受int参数并将其传递给gainTokens()方法。
任何有关如何解决该问题的信息将不胜感激。