Get a Windows Forms control by name in C#

后端 未结 14 1800
野性不改
野性不改 2020-11-22 09:22

I have a ToolStripMenuItem called myMenu. How can I access this like so:

/* Normally, I would do: */
this.myMenu... etc.

/* But ho         


        
14条回答
  •  甜味超标
    2020-11-22 09:52

    Using the same approach of Philip Wallace, we can do like this:

        public Control GetControlByName(Control ParentCntl, string NameToSearch)
        {
            if (ParentCntl.Name == NameToSearch)
                return ParentCntl;
    
            foreach (Control ChildCntl in ParentCntl.Controls)
            {
                Control ResultCntl = GetControlByName(ChildCntl, NameToSearch);
                if (ResultCntl != null)
                    return ResultCntl;
            }
            return null;
        }
    

    Example:

        public void doSomething() 
        {
                TextBox myTextBox = (TextBox) this.GetControlByName(this, "mytextboxname");
                myTextBox.Text = "Hello!";
        }
    

    I hope it help! :)

提交回复
热议问题