2016-06-12 115 views
2

當我寫代碼來添加用戶控件的形式:表格查找用戶控件添加

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

然後,我發現用戶控件的形式:

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

但結果是空& & tbxs。長度= 0 請指導我解決過程中的問題。非常感謝!

+0

是'wpf'還是'winform'? – Shaharyar

+0

每次有人試圖在沒有MVVM的情況下使用WPF時,上帝會讓一隻小貓浪費兩天的時間完成一項十分鐘的小任務。 –

回答

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"); 
      } 
     } 
    } 
}