btn2'在当前上下文中不存在
本文关键字:上下文 不存在 btn2 | 更新日期: 2023-09-27 18:17:30
下面我放了一些代码的问题是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显示奖品。标签(这是12个按钮的标签之一)。
我想这就是你想要的:
object tag;
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;
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 = '" + tag != null ? tag : "" + "'";
textBox5.Text = comando.ExecuteScalar().ToString();
}
}