0
    private void CreatingNewButtons()
    {
        int horizotal = 30;
        int vertical = 30;
        DataTable dt = Product.getAllProducts();
        Button[] buttonArray = new Button[dt.Rows.Count];

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            string name = dt.Rows[i][0].ToString();
            string price = dt.Rows[i][1].ToString();
            // byte[] getImg = dt.Rows[i][2];
            buttonArray[i] = new Button();
            buttonArray[i].Size = new Size(110, 110);
            buttonArray[i].Location = new Point(horizotal, vertical);
            buttonArray[i].Text = "" + name + "  Rs :" + price + "";
            if ((i == 5) || (i == 11) || (i == 17) || (i == 23) || (i == 29) ||
             (i == 35)) //|| (i == 62) || (i == 71))
            {
                vertical = 30;
                horizotal = horizotal + 130;//depaththe ida
            }
            else
                vertical = vertical + 130;
            tabControl1.TabPages[0].Controls.Add(buttonArray[i]);
            tabPage1.AutoScroll = true;
        }

    }

Using this code I create the button array and set buttons text from database as above. Now I want to get that text to string when clicked a button.

3
  • You forget to add an event handler for the click over the button. Without it your code cannot know which button has been clicked Commented Jan 26, 2019 at 14:33
  • You may create a common eventhandler for the button you are creating in the loop. In the code that handles the event, you can refer to sender variable to evaluate the button which triggered the click event, using which you can inspect its Text property. Commented Jan 26, 2019 at 14:33
  • As a side note, I suggest you to look at the TableLayoutPanel control to ease the burden to add the buttons and keep them in the proper position Commented Jan 26, 2019 at 14:36

1 Answer 1

0

First assign the event handler.

buttonArray[i].Click += new EventHandler(ButtonClick);

Then in the method, detect the click.

    private void ButtonClick(object sender, EventArgs e)
    {
        //To Do - Click Event
        Button btn = sender as Button;
        MessageBox.Show(btn.Text);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Or just += ButtonClick;, no need to write so much
Thank You So much Problem Solved..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.