Pergunta

Below i put some part of the code the problem is btn2.tag. it says " The name 'btn2' does not exist in the current context " how can i fix the issue? what is(are) the way(s)?

    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();
        }

}

//////

i have some buttons(12) in this example and when i click on the button5 and when i click on the button5, i want to display prize according to the btn2.Tag ( which is one of the 12 button's tag) .

how will i make it.

Foi útil?

Solução

I think this is what you want:

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();
    }
 }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top