我有大约 60 个文本框,当每个文本框都有自己的代码部分时,它会变得一团糟。对于某些事件,动作是相同的,而对于其他事件,可以有一个带有动作的字典。问题是我不知道如何遍历文本框、获取当前文本框引用并运行一些方法来更改当前文本框的文本。
UPD:我要做的是让所有文本框运行AllTextboxesEnter
方法,该方法将根据文本框的名称更改其文本,运行AllTextboxesLeave
方法将根据文本框的名称从动作字典中执行一些操作。
您可以尝试使用此代码
foreach( var control in this.Controls.OfType<TextBox>() )
{
control.Text = "";
}
你的问题还很不清楚,但我怀疑你想要这样的东西:
foreach (var textBox in Controls.OfType<TextBox>())
{
textBox.Text = /* insert action here */
}
目前尚不清楚动作字典的来源......
假设我正确理解了这个问题,这是我对问题解释的回答
private void Form1_Load(object sender, EventArgs e)
{
foreach (TextBox tb in this.Controls.OfType<TextBox>())
{
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";
}
我想我理解被问到的内容:
更新
此版本更好,因为它与通过设计器(模拟 InitializeControls)创建的文本框一起使用,并且它使用字典来定位在字典中找到的文本框。如果 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<string, string> TextBoxEnterText = new Dictionary<string, string>
{
{ "T1", "Enter T1" },
{ "T2", "Enter T2" },
{ "T3", "Enter T3" },
{ "T4", "Enter T4" },
{ "T5", "Enter T5" },
};
private static readonly Dictionary<string, string> TextBoxLeaveText = new Dictionary<string, string>
{
{ "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];
}
}