代码之家  ›  专栏  ›  技术社区  ›  user241423

如何为文本框数组创建处理事件

  •  3
  • user241423  · 技术社区  · 16 年前

    我创建数组:

    TextBox[] textarray = new TextBox[100];
    

    然后在循环中设置此参数,所有项目数组都位于uniformgrid1中

    textarray[i] = new TextBox();
            textarray[i].Height = 30;
            textarray[i].Width = 50;
            uniformGrid1.Children.Add(textarray[i]);
    

    如何创建事件单击或双击所有项数组?
    对不起我的英语。

    3 回复  |  直到 16 年前
        1
  •  2
  •   Asad    16 年前
     public static void blah()
            {
                TextBox[] textarray = new TextBox[100];
                List<TextBox> textBoxList = new List<TextBox>();
                for (int i = 0; i < textarray.Length; i++)
                {
                    textarray[i] = new TextBox();
                    textarray[i].Height = 30;
                    textarray[i].Width = 50;
    
                    // events registration
                    textarray[i].Click += 
                          new EventHandler(TextBoxFromArray_Click);
                    textarray[i].DoubleClick += 
                          new EventHandler(TextBoxFromArray_DoubleClick);
                }
            }
    
            static void TextBoxFromArray_Click(object sender, EventArgs e)
            {
                // implement Event OnClick Here
            }
    
            static void TextBoxFromArray_DoubleClick(object sender, EventArgs e)
            {
                // implement Event OnDoubleClick Here
            }
    

    编辑:

    根据 @ Aaronaugh 建议:

    textarray[i].Click += TextBoxFromArray_Click;
    textarray[i].DoubleClick += TextBoxFromArray_DoubleClick;
    
        2
  •  2
  •   Reed Copsey    16 年前

    只需添加单击或双击事件处理程序。例如,要捕获双击事件:

    textarray[i] = new TextBox();
    textarray[i].Height = 30;
    textarray[i].Width = 50;
    textarray[i].MouseDoubleClick += this.OnMouseDoubleClick;
    
    uniformGrid1.Children.Add(textarray[i]);
    

    为了实现上述功能,您需要一个方法,如:

    void OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        // Do something
    }
    
        3
  •  0
  •   Anthony Pegram    16 年前

    创建一个单击事件处理程序,然后使用它订阅文本框的单击事件,如下所示:

    textarray[i].Click += new EventHandler(textbox_Click);
    
    ...
    
    void textbox_Click(object sender, EventArgs e)
    {
        // do something 
    }
    

    如果要对每个文本框执行相同的操作,则一个单击处理程序就足够了。