Home > Back-end >  Access an object through its name as a string c#
Access an object through its name as a string c#

Time:12-11

I try to find out, how it is possible to access an object through a string which has the same name as the object name. for example, I want to change the property of n times of Buttons using for loop

    public static object GetObject(string ObjectName)
    {
        // this Method has to return an Object through his name     
    }
    for (int i = 1; i < 4; i  )
        {
            GetObject(Convert.ToString("Button"  i) ).Text = Convert.ToString(i);
        }

    }
  

}

this code has the same function of this code

Button1.Text = "1";
Button2.Text = "2";
Button3.Text = "3";

CodePudding user response:

You can develop different types of applications using C#. i.e. Web, WinForms, WPF. They have different types of Control and Type. I'm assuming that you are developing a WinForms application. In that case, you can use the Controls property of a WinForm to access all the Controls of a Form.

Please check the below code block for the implementation:

    public object GetObject(string ObjectName)
    {
        // this Method has to return an Object through his name     
        Control myControl = Controls.Find(ObjectName, true).FirstOrDefault();
        if (myControl != null)
        {
            // Do Stuff
            return myControl;
        }
        else return null;
    }

    private void RenameButtons()
    {
        for (int i = 1; i < 4; i  )
        {
            //GetObject(Convert.ToString("Button"   i)).Text = Convert.ToString(i);
            object btn = GetObject(Convert.ToString("Button"   i));
            if (btn != null) ((Button)btn).Text = Convert.ToString(i);
        }
    }

Output

You will find more details about the Controls property by following this link.

CodePudding user response:

you can try this

foreach (Control control in Controls)
{
   var btn = control as Button;

  if ( btn != null && btn.Name.StartsWith("Button") )
  {
      var i= btn.Name.Substring(6, 1)

       //if( i.Convert.ToInt32() <4 )  //optional
      btn.Text = i;
   }
}
  • Related