如何遍历所有文本框并使它们从动作字典中运行相应的操作?

我有大约60个文本框,当每个文本框都有自己的代码部分时,它会很乱。 对于某些事件,操作是相同的,而对于其他事件,可以有一个包含操作的字典。 问题是我不知道如何遍历文本框,获取当前文本框引用并运行一些方法来更改当前文本框的文本。

UPD:我要做的是让所有文本框运行AllTextboxesEnter方法,该方法将根据文本框的名称更改其文本,运行AllTextboxesLeave方法,该方法将根据文本框的名称从操作字典执行某些操作。

假设我正确理解了这个问题,这是我对问题解释的答案

 private void Form1_Load(object sender, EventArgs e) { foreach (TextBox tb in this.Controls.OfType()) { tb.Enter += new EventHandler(textBoxAll_Enter); tb.Leave += new EventHandler(textBoxAll_Leave); } } private void textBoxAll_Enter(object sender, EventArgs e) { ((TextBox)sender).Text = "textbox gained focus"; } private void textBoxAll_Leave(object sender, EventArgs e) { ((TextBox)sender).Text = "textbox lost focus"; } 

您可以尝试使用此代码

 foreach( var control in this.Controls.OfType() ) { control.Text = ""; } 

你的问题还远未明确,但我怀疑你想要的东西如下:

 foreach (var textBox in Controls.OfType()) { textBox.Text = /* insert action here */ } 

目前还不清楚行动词典在哪里进来……

我想我理解的是:

更新

这个版本更好,因为它适用于通过设计器创建的TextBoxes(模拟的InitializeControls),并且它使用Dictionaries来定位在字典中找到的TextBox。 如果TextBoxes包含在子容器中,Controls.Find非常有用。

 using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Windows.Forms; class Form1 : Form { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } private static readonly Dictionary TextBoxEnterText = new Dictionary { { "T1", "Enter T1" }, { "T2", "Enter T2" }, { "T3", "Enter T3" }, { "T4", "Enter T4" }, { "T5", "Enter T5" }, }; private static readonly Dictionary TextBoxLeaveText = new Dictionary { { "T1", "Leave T1" }, { "T2", "Leave T2" }, { "T3", "Leave T3" }, { "T4", "Leave T4" }, { "T5", "Leave T5" }, }; private void InitializeControls() { Controls.Add(new TextBox { Name = "T1", Location = new Point(10, 10) }); Controls.Add(new TextBox { Name = "T2", Location = new Point(10, 40) }); Controls.Add(new TextBox { Name = "T3", Location = new Point(10, 70) }); Controls.Add(new TextBox { Name = "T4", Location = new Point(10, 100) }); Controls.Add(new TextBox { Name = "T5", Location = new Point(10, 130) }); } public Form1() { InitializeControls(); foreach (string name in TextBoxEnterText.Keys) Controls.Find(name, true).First().Enter += textBox_Enter; foreach (string name in TextBoxLeaveText.Keys) Controls.Find(name, true).First().Leave += textBox_Leave; } static void textBox_Leave(object sender, EventArgs e) { TextBox textBox = (TextBox)sender; textBox.Text = TextBoxLeaveText[textBox.Name]; } static void textBox_Enter(object sender, EventArgs e) { TextBox textBox = (TextBox)sender; textBox.Text = TextBoxEnterText[textBox.Name]; } }