【问题标题】:I wonder if there is a way to know which button from a list i clicked [duplicate]我想知道是否有办法知道我点击了列表中的哪个按钮[重复]
【发布时间】:2018-05-12 23:20:51
【问题描述】:

我在 windowsformapplication 中编码,c# 这就是我到目前为止所做的事情

    List<Button> list = new List<Button>();
    private void Form1_Load(object sender, EventArgs e)
    {

        for (int j = 0; j <= 13; j++)
        {
            for (int i = 0; i <= 13; i++)
            {
                Button ruta = new Button();
                ruta.Location = new Point(0+ (i * 50), 0 + (j * 50));
                ruta.Size = new Size(50, 50);
                ruta.AutoSize = false;
                ruta.Text = "";
                ruta.TabStop = false;
                list.Add(ruta);
                this.Controls.Add(ruta);
            }
        }
    }

我现在想要的是能够单击这些按钮,然后将文本框的文本更改为按下按钮的索引,当涉及到 C# 时,我是一个真正的菜鸟,所以我不知道是什么我在做自动取款机。 我的想法是这样的

     private void ruta_click(object sender, EventArgs e)
      {
        txtBox.text = list.SelectedItemIndex();
      }

这显然行不通,因为 SelectedItemIndex() 不是真正的方法,而只是一个示例。

【问题讨论】:

  • 发件人....是线索...

标签: c#


【解决方案1】:

您应该在列表中查找sender 的索引。发送者将是被点击的按钮,通常sender 将是触发事件的控件。另外不要忘记将处理程序添加到按钮,因为您现在没有在 for 中执行此操作。

private void Form1_Load(object sender, EventArgs e)
{

    for (int y = 0; y <= 13; y++)
    {
        for (int i = 0; i <= 13; i++)
        {
            Button ruta = new Button();
            ruta.Location = new Point(0 + (i * 50), 0 + (y * 50));
            ruta.Size = new Size(50, 50);
            ruta.AutoSize = false;
            ruta.Text = "";
            ruta.TabStop = false;
            ruta.Click += ruta_click;
            list.Add(ruta);
            this.Controls.Add(ruta);
        }
    }
}

private void ruta_click(object sender, EventArgs e)
{
    txtBox.Text = list.IndexOf((Button)sender) + "";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多