//这是一个窗体应用程序(不是web的)
//目的是全手机制作控件,在p1(panel)中生成一个文本框t1,给t1添加了双击事件
//当在t1中输入一个数,双击t1时输出这个数的平方值.
//现在问题是:自定义的控件能正常显示,也能触发双击事件,但不能引用t1,因为找不到t1
//麻烦高手帮我看看,在下万分感谢了!!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace WindowsFormsApplication14
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
       Panel p1 = new Panel();
       Label L1 = new Label();
       TextBox t1 = new TextBox();
        private void Form1_Load(object sender, EventArgs e)
        {
            p1.Size = new Size(300, 200);
            p1.Location = new Point(200, 100);
            p1.BackColor = SystemColors.AppWorkspace;
            this.Controls.Add(p1);
            
            L1.Text = "请输入一个数:";
            p1.Controls.Add(L1);
           
            t1.Location = new Point(20, 30);
            t1.Text = "";
            p1.Controls.Add (t1);
            //以上完成控件界面制作.下面给文本框t1添加事件及代码(本处是把生成的控件置放在panel(p1)内部的
           // t1.Click += new System.EventHandler(t1_Click);
            t1.DoubleClick += new System.EventHandler(t1_DoubleClick);
            
        }       
        private void t1_DoubleClick(object sender, EventArgs e)
        {
            Panel p2 = (Panel)(this.Controls.Find("p1", true)[0]);  
//问题出在这里了? 提示索引下标越界,肯定是没找到p1控件了
//我试着把p1,t1定义在方法的外面通用处,不定期是解决不了这个问题
           // Panel p2 =(Panel)( this.Controls["p1"]);//也样试也不行
           // TextBox tt = (TextBox)(p2.Controls.Find("t1", true)[0]); 
//p1找不到,就提示p2没实例化.         
            TextBox tt = (TextBox)p2.Controls["t1"];
            int n = int.Parse(tt.Text );
            MessageBox.Show((n * n).ToString());
        }
    }
}
c#.net自定义控件