我正在使用c#处理Windows窗体应用程序项目,并且我正在尝试使用相同的事件操作创建一个TextBox数组。我的意思是需要N个TextBoxes(N与用户分配不同),而所有“TextBox_TextChanged”事件都是相同的。如果你能帮助我,我将不胜感激。
答案 0 :(得分:0)
在下面找到
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)
{
}
答案 1 :(得分:0)
请试一试。
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)
{
}
答案 2 :(得分:0)
我刚遇到类似你的问题,我可以详细说明我的解决方案:
将数组声明为类中的字段:
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");
}
如果你必须填写表布局面板控件(同一行)中的内容,那么你可以使用数组中的位置。