110,536
社区成员
发帖
与我相关
我的任务
分享
foreach (Control ctrl in groupBox1.Controls)
{
if (ctrl is TextBox || ctrl is ComboBox)
ctrl.Text = "";
}
foreach (Control ctrl2 in panel1.Controls)
{
if (ctrl2 is TextBox || ctrl2 is ComboBox)
ctrl2.Text = "";
}
foreach (Control ctrl2 in panel2.Controls)
{
if (ctrl2 is TextBox || ctrl2 is ComboBox)
ctrl2.Text = "";
}
foreach (Control ctrl2 in panel3.Controls)
{
if (ctrl2 is TextBox || ctrl2 is ComboBox)
ctrl2.Text = "";
}
foreach (Control ctrl2 in panel4.Controls)
{
if (ctrl2 is TextBox || ctrl2 is ComboBox)
ctrl2.Text = "";
}
public void Test(Control ctr)
{
foreach (Control ctrl in ctr.Controls)
{
if (ctrl is TextBox || ctrl is ComboBox)
ctrl.Text = "";
}
}
谈不上什么优化,
只是精简,重用了方法。
public partial class Form1 : Form
{
private List<Control> _allControls;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GetAllControls();
}
private void GetAllControls()
{
foreach (Control ctrl1 in Controls)
{
_allControls.Add(ctrl1);
}
foreach (Control ctrl2 in panel1.Controls)
{
_allControls.Add(ctrl2);
}
foreach (Control ctrl3 in panel2.Controls)
{
_allControls.Add(ctrl3);
}
}
private void SetMyControlValue()
{
foreach (Control ctrl in _allControls)
{
if (ctrl is MyTextBox || ctrl is MyComboBox)
{
ctrl.Text = "";
}
}
}
}
List<Control> all=new List<Control>();
all.AddRange(groupBox1.Controls);
foreach (Control ctrl2 in all)
{
if (ctrl2 is TextBox || ctrl2 is ComboBox)
ctrl2.Text = "";
}