具有相同事件的文本框数组

array of textboxes with the same event

我正在使用 c# 开发一个 windows 表单应用程序项目,我正在尝试制作一个具有相同事件操作的 TextBox 数组。我的意思是需要 N 个文本框(N 因用户分配而不同),而所有“TextBox_TextChanged”事件都是相同的。如果你能帮助我,我将不胜感激。

在下面找到

        TextBox t1 = new TextBox();
        TextBox t2 = new TextBox();
        TextBox t3 = new TextBox();
        TextBox t4 = new TextBox();
        TextBox t5 = new TextBox();
        TextBox t6 = new TextBox();

        private void Form1_Load(object sender, EventArgs e)
        {
            TextBox[] tBoxes = { t1, t2, t3, t4, t5, t6 };

            foreach (TextBox item in tBoxes)
            {
                item.TextChanged += text_Changed;
            }
        }

        private void text_Changed(object sender, EventArgs e)
        {

        }

请试试这个。

    private void frmMain_Load(object sender, EventArgs e)
    {
           int userPermittedCount = 4 // You can add user defined permission no : of text box count here;
           int pointX = 30;
           int pointY = 40;

           for (int i = 0; i < userPermittedCount; i++)
           {
              TextBox txtBox = new TextBox();
              txtBox.Location = new Point(pointX, pointY);
              this.Controls.Add(txtBox);
              this.Show();
              pointY += 20;
              txtBox.TextChanged += txtAdd_TextChanged;
            }
   }

 private void txtAdd_TextChanged(object sender, EventArgs e)
 {
 }

我刚刚 运行 遇到了与您类似的问题,我可以详细说明我的解决方案:

在您的 class 中将数组声明为字段:

private TextBox() yourArrayOfTextboxes;

在一个方法中添加这个循环填充数组的内容:

yourArrayOfTextboxes=new TextBox [howManyTextboxesYouWishInTheArray];

for (int i=0,i<howManyTextboxesYouWishInTheArray, i++)
//note arrays' indexes start from 0
{
 yourArrayOfTextboxes[i]=new TextBox() {Text="some Text",ForeColor=Color.SomeColor,BackColor=Color.SomeColor,Name="TextBox"+i};
someControl.Controls.Add(yourArrayOfTextboxes[i]);
//"someControl" is a name of a control which will be the parent of the newly generated TextBox member, in case you have none (could be a Panel control, or a Table Layout Panel, or a groupBox whatever
if(yourArrayOfTextboxes[i]!=null)
 {
yourArrayOfTextboxes[i].TextChanged+=theNameOfYourMainForm_TextChanged;
 }
}

然后,填写 _TextChanged 事件本身:

//appeal to the TextBox which fired up the event by (sender as TextBox)

private void theNameOfYourMainForm_TextChanged(object sender,EventArgs e)
{
int intArrayPosition=int.Parse((sender as TextBox).Name.Substring((sender as TextBox).Name.Length-1));  //in case you need the position in the array where it fired up;
MessageBox.Show((sender as TextBox).Name+"fired up the TextChanged event");
}

如果您最终遇到某些情况,当您必须像我一样在 Table 布局面板控件(同一行)中填充内容时,您可以使用数组中的位置。