如何定位我用for循环创建的特定按钮?

时间:2017-10-13 03:14:40

标签: c# asp.net button

我创建一个带有for循环的4个按钮,我想要定位一个特定的按钮,说一个名称为3的按钮,并对它做一些事情,就像让它看不见一样。任何人都知道如何做到这一点?

<configuration>
  <property>
     <name>dfs.replication</name>
     <value>1</value>
  </property>
  <property>
     <name>dfs.namenode.name.dir</name>
     <value>file:/usr/local/hadoop_work/hdfs/namenode</value>
  </property>
  <property>
    <name>dfs.namenode.checkpoint.dir</name>
    <value>file:/usr/local/hadoop_work/hdfs/namesecondary</value>
  </property>
  <property>
     <name>dfs.datanode.data.dir</name>
     <value>file:/usr/local/hadoop_work/hdfs/datanode</value>
  </property>
  <property>
    <name>dfs.secondary.http.address</name>
    <value>xxx.xxx.xxx.xxx:50090</value>
  </property>
<property> 
<name>dfs.block.size</name> 
<value>134217728</value> 
<description>Block size</description> 
</property>
</configuration>

2 个答案:

答案 0 :(得分:0)

您可以将按钮保存在数组(或其他集合)中:

        Button[] buttons = new Button[4];
        for (int j = 0; j < 4; j++)
        {
            Button b = new Button();
            b.Left = x;
            b.Top = y;
            b.Width = WIDTH;
            b.Height = HEIGHT;
            b.Name = counter.ToString();

            counter++;
            x += VGAP + HEIGHT;
            this.Controls.Add(b); 
            buttons[i] = b;
        }

        //....
        button[3].Visible = false;

答案 1 :(得分:0)

由于按钮是动态创建的,因此您无法使用Name属性直接在代码中引用它们 您可以将创建的按钮存储在列表中。然后在给定索引处使用所需按钮执行某些操作。请参阅以下代码:

public partial class Form1 : Form
{
    int x, y;
    private const int WIDTH = 50;
    private const int HEIGHT = 50;
    private const int VGAP = 5;
    List<Button> lstButtons = new List<Button>();


    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        int counter = 1;
        for (int j = 0; j < 4; j++)
        {
            Button b = new Button();
            b.Left = x;
            b.Top = y;
            b.Width = WIDTH;
            b.Height = HEIGHT;
            b.Name = counter.ToString();

            counter++;
            x += VGAP + HEIGHT;
            this.Controls.Add(b);
            lstButtons.Add(b);

        }

        DosomethingWithButton(3);
    }

    private void DosomethingWithButton(int index)
    {
        lstButtons[index].Text = "Hello";
    }
}