|
<< Click to Display Table of Contents >> Reflection - percorrendo TextBox |
![]() ![]()
|
Tela

Form.cs
using System;
using System.Reflection;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Control FindControlByName(Control pai, string name)
{
foreach (Control c in pai.Controls)
{
if (c.Name == name)
return c; //found
// se o o controle tiver filhos, chama recursivamente a função
if (c.Controls.Count > 0)
{
Control retorno = FindControlByName(c, name);
// o retorno não é null, então acabou! é tetra!
if (retorno != null)
return retorno;
}
}
return null; //not found
}
private void btLimparTODOS_Click(object sender, EventArgs e)
{
FieldInfo[] campos = this.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
foreach (FieldInfo campo in campos)
if (campo.FieldType == typeof(TextBox))
{
TextBox t = (TextBox)FindControlByName(this, campo.Name);
t.Clear();
}
}
private void btLerTODOS_Click(object sender, EventArgs e)
{
string texto = string.Empty;
FieldInfo[] campos = this.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
foreach (FieldInfo campo in campos)
if (campo.FieldType == typeof(TextBox))
{
TextBox t = (TextBox)FindControlByName(this, campo.Name);
texto += campo.Name + "=" + t.Text + "\n";
}
MessageBox.Show(texto);
}
}
}