我使用数组创建Buttons,所以我想在单击数组的按钮时将button的文本值转换为变量,该怎么做?

时间:2019-01-26 14:30:40

标签: c# winforms

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

    }

使用此代码,我如上所述创建按钮数组并设置数据库中的按钮文本。现在,我想单击按钮时将该文本转换为字符串。

1 个答案:

答案 0 :(得分:0)

首先分配事件处理程序。

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

然后在方法中,检测点击。

    private void ButtonClick(object sender, EventArgs e)
    {
        //To Do - Click Event
        Button btn = sender as Button;
        MessageBox.Show(btn.Text);
    }
}