添加时在表单中查找UserControl

时间:2016-06-12 16:44:37

标签: c# wpf winforms

我编写代码以在Form中添加UserControl:

        UserControl edt = new UserControl();
        edt.Name = "ItemEdit";
        frm_Editor frm = new frm_Editor();
        frm.Controls.Add(edt);
        frm.Show();

然后,我在Form中找到UserControl:

Control[] tbxs = this.Controls.Find("ItemEdit", true);
if (tbxs != null && tbxs.Length > 0)
{
    MessageBox.Show("Found");
}

但结果是null&& tbxs.Length = 0 请指导我处理问题的解决方案。非常感谢!

1 个答案:

答案 0 :(得分:0)

它可以在这个小程序中运行,它可能会指向您使用自己的代码的解决方案。

using System;
using System.Windows.Forms;

namespace FormTest
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Form1 frm = new Form1();
            UserControl edt = new UserControl();
            edt.Name = "ItemEdit";
            frm.Controls.Add(edt);

            Application.Run(frm);
        }
    }
}

using System.Windows.Forms;

namespace FormTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            Control[] tbxs = this.Controls.Find("ItemEdit", true);
            if (tbxs != null && tbxs.Length > 0)
            {
                MessageBox.Show("Found");
            }
        }
    }
}