SoFunction
Updated on 2025-02-28

C# implements the method of obtaining controls based on specified containers and control names

This article describes the method of obtaining controls based on the specified container and control name of C#, which has certain reference value when designing C# applications. Share it for your reference. The specific implementation method is as follows:

The function code is as follows:

/// <summary>
/// Obtain control based on the specified container and control name/// </summary>
/// <param name="obj">Container</param>/// <param name="strControlName">Control name</param>/// <returns>Control</returns>private object GetControlInstance(object obj,string strControlName)
{
 IEnumerator Controls = null;//All controls Control c = null;//Current control Object cResult=null;//Find the results if(() == ())//Form {
 Controls = ();
 }
 else//Control {
 Controls = ((Control)obj).();
 }
 while(())//Travel operation {
 c = (Control);//Current control if()//The current control is a container {
  cResult = GetControlInstance(c,strControlName);//Recursive search  if(cResult==null)//Not in the current container, jump out and continue to search  continue;
  else//Finish the control and return  return cResult;
 }
 else if( == strControlName)//Not a container, find the control at the same time, return {
  return c;
 }
 }
 return null;//The control does not exist}

Examples are as follows:

((Button) GetControlInstance(this,"button7")).BackColor = ;
((Button) GetControlInstance(this.groupBox4,"button7")).PerformClick();

I hope that the examples described in this article will be helpful to everyone's C# programming.