我有一个onLoad
事件,它包含从数据库中获取数据的变量,现在我需要将该字符串传递给按钮的onclick
事件,以便无论何时按下它,我都可以执行操作。我需要从加载到onclick
访问单词变量。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public string word, alphabets;
public int chances, score;
public Form2()
{
InitializeComponent();
}
public void Form2_Load(object sender, EventArgs e)
{
chances = 8;
score = 0;
alphabets = "abcdefghijklmnopqrstuvwxyz";
Random rnd = new Random();
int wordid = rnd.Next(1, 127);
label12.Text = chances.ToString();
label13.Text = score.ToString();
try
{
string myConnection1 = "datasource=localhost;port=3306;username=root;password=amit;";
MySqlConnection myConn1 = new MySqlConnection(myConnection1);
myConn1.Open();
int count = 0;
var cmd = new MySqlCommand(" select words from gamers.gamewords where id='" + wordid + "';", myConn1);
string word = (string)cmd.ExecuteScalar();
int length = word.Length;
label4.Text = length.ToString();
label7.Text = alphabets;
label14.Text = word;
myConn1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void button1_Click(object sender, EventArgs e)
{
//Code for Game Begins
int i = 0, j = 0;
int lengthcount = 0;
string choice = textBox1.Text;
string guess;
label14.Text = word + "**";
// for (i = 0; i<word.Length; i++)
/* {
if (word[i] == choice[0])
{
label14.Text = "Good Guess! You Scored a point";
lengthcount++;
score += 5;
guess = choice;
label9.Text= guess;
}
else
{
chances--;
guess = "______";
if (chances == 0)
{
label14.Text = "You Lost the Game! Turns Over";
button1.Enabled = false;
}
else
{
label14.Text = "Sorry! Try Again";
}
}
}*/
}
}
}
你可以像调用方法一样调用button1_Click
,但不能直接向其传递值,因为Click
事件由默认EventHandler
处理,所以你只有两个参数:object sender
和EventArgs e
:
button1_Click(sender, e);
但是您可以使用Form2
类中的属性(或字段/变量(来保存Form2_Load
方法中的值,并在读取后在button1_Click
方法中保存:
public partial class Form2 : Form
{
// ...
private string ValueToHold { get; set; }
// ...
public void Form2_Load(object sender, EventArgs e)
{
// ...
ValueToHold = "something";
// ...
}
public void button1_Click(object sender, EventArgs e)
{
// ...
// Use the ValueToHold here!
// ...
}
}