【问题标题】:I create Buttons Using array so I want to get text value of button to variable when clicked a button of a array how can I do this? [duplicate]我使用数组创建按钮,所以我想在单击数组的按钮时获取按钮的文本值到变量我该怎么做? [复制]
【发布时间】:2019-01-26 22:40:14
【问题描述】:
    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;
        }

    }

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

【问题讨论】:

  • 您忘记为单击按钮添加事件处理程序。没有它,您的代码将无法知道单击了哪个按钮
  • 您可以为您在循环中创建的按钮创建一个通用事件处理程序。在处理事件的代码中,您可以参考sender变量来评估触发点击事件的按钮,使用它您可以检查其Text属性。
  • 附带说明,我建议您查看TableLayoutPanel 控件以减轻添加按钮的负担并将它们保持在适当的位置

标签: c# winforms


【解决方案1】:

首先分配事件处理程序。

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

【讨论】:

  • 或者就+= ButtonClick;,不用写那么多
  • 谢谢你解决了这么多问题..
猜你喜欢
  • 2018-04-28
  • 1970-01-01
  • 2022-12-06
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
  • 2013-02-12
  • 2021-01-15
  • 1970-01-01
相关资源
最近更新 更多