Get a Windows Forms control by name in C#

后端 未结 14 1523
野性不改
野性不改 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

    this.Controls.Find(name, searchAllChildren) doesn't find ToolStripItem because ToolStripItem is not a Control

      using SWF = System.Windows.Forms;
      using NUF = NUnit.Framework;
      namespace workshop.findControlTest {
         [NUF.TestFixture]
         public class FormTest {
            [NUF.Test]public void Find_menu() {
               // == prepare ==
               var fileTool = new SWF.ToolStripMenuItem();
               fileTool.Name = "fileTool";
               fileTool.Text = "File";
    
               var menuStrip = new SWF.MenuStrip();
               menuStrip.Items.Add(fileTool);
    
               var form = new SWF.Form();
               form.Controls.Add(menuStrip);
    
               // == execute ==
               var ctrl = form.Controls.Find("fileTool", true);
    
               // == not found! ==
               NUF.Assert.That(ctrl.Length, NUF.Is.EqualTo(0)); 
            }
         }
      }
    

提交回复
热议问题