在网上找了段代码,是动态创建控件的,但没有办法获取这个控件的真实类型引用.
因为还要操作它的属性和方法.求解.如何实现动态创建控件并且可以读写其属性,以及方法...注:因为控件类型和个数都比较多,用if case等会崩溃掉的,.net没这么笨吧
public static void CreateControl(string controlType, Form form, int positionX, int positionY){try{ string assemblyQualifiedName =  typeof(System.Windows.Forms.Form).AssemblyQualifiedName;string assemblyInformation = assemblyQualifiedName.Substring(assemblyQualifiedName.IndexOf(","));Type ty = Type.GetType(controlType + assemblyInformation);Control newControl = (Control)System.Activator.CreateInstance(ty);form.SuspendLayout();newControl.Location = new System.Drawing.Point(positionX, positionY);newControl.Name = ty.Name + form.Controls.Count.ToString();form.Controls.Add(newControl);form.ResumeLayout();}catch(Exception ex){throw ex;}}调用: CreateControl("System.Windows.Forms.TextBox", this, 10, 10);

解决方案 »

  1.   

            public static void CreateControl(string controlType, string name,Form form, int positionX, int positionY)
            {            try
                {                string assemblyQualifiedName = typeof(System.Windows.Forms.Form).AssemblyQualifiedName;                string assemblyInformation = assemblyQualifiedName.Substring(assemblyQualifiedName.IndexOf(","));                Type ty = Type.GetType(controlType + assemblyInformation);                Control newControl = (Control)System.Activator.CreateInstance(ty);    
                    form.SuspendLayout();                newControl.Location = new System.Drawing.Point(positionX, positionY);                newControl.Name = name;// ty.Name + form.Controls.Count.ToString();                form.Controls.Add(newControl);                form.ResumeLayout();            }            catch (Exception ex)
                {
                    throw ex;
                }        }        private void button1_Click(object sender, EventArgs e)
            {
                CreateControl("System.Windows.Forms.TextBox","MyName", this, 10, 10);
                this.Controls["MyName"].Text = "ss";
            }
      

  2.   

    LZ,其实动态添加最主要的就是this.Controls.Add(你想要添加的控件);这句话,只要使用它,你动态创建的控件就能添加到窗体里面去
      

  3.   

    这个问题真难表达清楚.
    比如要创建System.Windows.Forms.TextBox这个控件,并且这个控件的类型是从外部读取过来的字符串...
    并且外部配置的随时都可能发生变化,,种类也不限定,所以不是直接new一个过来完事,因为程序编译前并不知道要new一个什么类型的控件...
    最要命的,就是连操作控件的属性和方法名也是从外部读取的.
    this.Controls["MyName"].Text = "ss";
    这个时候还不知道有Text这个属性呢...
    在程序编写的过程中并不知道它有具体某个属性或方法..除非if判断它的类型typeOf(),显得太笨了...
      

  4.   

    LZ,你只要在项目中添加一个用户控件。
    原后把你创建控件的那个代码写到.CS文件里。
    生成一下。你的工具箱里就会有这个控件
    原后拉出来用就OK拉~很简单的