[WinForm] FindControl, winformfindcontrol
Key code:
/// <Summary> /// query the control by name /// </summary> /// <param name = "parentControl"> query the control's parent container control </param> /// <param name = "findCtrlName"> Search for the Control name </param> /// <returns> If no result is found, NULL is returned. </returns> public static Control FindControl (this Control parentControl, string findCtrlName) {Control _ findedControl = null; if (! String. IsNullOrEmpty (findCtrlName) & parentControl! = Null) {foreach (Control ctrl in parentControl. controls) {if (ctrl. name. equals (findCtrlName) {_ findedControl = ctrl; break ;}} return _ findedControl ;} /// <summary> /// convert Control to a certain Control type /// </summary> /// <typeparam name = "T"> Control type </typeparam>/ // <param name = "control"> Control </param> /// <param name = "result"> Conversion result </param> /// <returns> If the conversion is successful returns the control; if a failure occurs, NULL </returns> public static T Cast <T> (thi S Control control, out bool result) where T: Control {result = false; T _ castCtrl = null; if (control! = Null) {if (control is T) {try {_ castCtrl = control as T; result = true;} catch (Exception ex) {Debug. writeLine (string. format ("an exception occurred while converting Control to a certain type of Control. Cause: {0}", ex. message); result = false ;}}return _ castCtrl ;}}
Test code:
bool _sucess = false; CheckBox _finded = panel1.FindControl("checkBox1").Cast<CheckBox>(out _sucess); if (_sucess) { MessageBox.Show(_finded.Name); } else { MessageBox.Show("Not Finded."); }
Hope this is helpful!
C # An error in FindControl when compiling an exe application.
WinForm does not have the FindControl function ..
If you must use FindControl
You can try to define
Private Control FindControl (string controlName)
{
FieldInfo field = this. GetType (). GetField (controlName, BindingFlags. Instance | BindingFlags. NonPublic );
If (field = null) return null;
Return field. GetValue (this) as Control;
}
PS:
Reference namespace using System. Reflection;
Or:
Private Control FindControl (string controlName)
{
Return this. Controls [controlName];
}
Can I use FindControl in winform? If not? How can I change the ID name of winform?
Is FindControl used to query a control in a control set? For example, the panl1.Controls. Find () method?