下面我放了部分代码,问题是 btn2.tag。它说“当前上下文中不存在名称'btn2'”我该如何解决这个问题?什么是(是)方式?
public Main()
{
InitializeComponent();
// bla bla bla
int NumOfButtons = 12;
int loc = 20;
int k = 5;
for (int i = 1; i <= NumOfButtons; i++)
{
Button btn = new Button();
{
lst.Location = new Point(4, 4);
btn.Size = new Size(55, 55);
btn.Tag = i;
command.CommandText = "select product_Name from T_Product where PRODUCT_ID = " + btn.Tag;
btn.Text = command.ExecuteScalar().ToString();
btn.Location = new Point(k, loc);
}
btn.Click += Buttons_Click;
}
private void Buttons_Click(System.Object sender, System.EventArgs e)
{
isclicked = true;
// Used "Sender" to know which button was clicked ?
Button btn = sender as Button;
Button btn2 = sender as Button;
btn2.Tag = btn.Tag;
}
private void button5_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
SqlConnection conn = new SqlConnection(@"server=.\SQLEXPRESS;Initial Catalog=DUK1;Integrated Security=True;Pooling=False");
command.Connection = conn;
conn.Open();
command.CommandText = "select product_PRIZE from T_Product where PRODUCT_ID = " + btn2.Tag; // here problem occurs
textBox5.Text = comando.ExecuteScalar().ToString();
}
}
//////
在这个例子中我有一些按钮(12),当我点击 button5 时,当我点击 button5 时,我想根据 btn2.Tag(这是 12 个按钮的标签之一)显示奖品。
我将如何做到。