如何动态的在webpartzone中添加控件

解决方案 »

  1.   

    下面是为在Form或Panel中创建控件的方法,可以参照一下.
    ///<summary>
            /// 在指定的容器中的指定位置创建指定类型的控件。
            /// </summary>
            /// <param name="abs_control">要创建的控件的相关信息(结构体)</param>
            /// <param name="ac_parentContainer">要在上面创建控件容器控件</param>
            /// <param name="int ai_positionX">要创建的控件的X坐标</param>
            /// <param name="int ai_positionY">要创建的控件的Y坐标</param>
            /// <param name="as_msg">错误返回信息</param>
            public int CreateControl(ButtonStruct abs_control, Control ac_parentContainer, int ai_positionX, int ai_positionY, out string as_msg)
            {
                as_msg = null;
                try
                {
                    string ls_assemblyQualifiedName = null;
                    if (ac_parentContainer is Form)
                    {
                        ls_assemblyQualifiedName = typeof(System.Windows.Forms.Form).AssemblyQualifiedName;
                    }
                    else if (ac_parentContainer is Panel)
                    {
                        ls_assemblyQualifiedName = typeof(System.Windows.Forms.Panel).AssemblyQualifiedName;
                    }
                    else
                    {
                        //as_msg = "暂不支持在" +typeof(ac_parentContainer).FullName.ToString() + "上面放置控件";
                        as_msg = "暂不支持在上面放置控件";
                        return -1;
                    }
                    string assemblyInformation = ls_assemblyQualifiedName.Substring(ls_assemblyQualifiedName.IndexOf(","));
                    Type lt_type = Type.GetType(abs_control.ls_type + assemblyInformation);
                    Control lc_newControl = (Control)System.Activator.CreateInstance(lt_type);
                    ac_parentContainer.SuspendLayout();
                    lc_newControl.Location = new System.Drawing.Point(ai_positionX, ai_positionY);
                    lc_newControl.Size = new System.Drawing.Size(abs_control.li_width, abs_control.li_height);
                    lc_newControl.Name = lt_type.Name + ac_parentContainer.Controls.Count.ToString();
                    lc_newControl.Text = abs_control.ls_text;
                    lc_newControl.Tag = abs_control.li_tag;
                    ac_parentContainer.Controls.Add(lc_newControl);
                    lc_newControl.Click += new EventHandler(NewControlClick);
                    ac_parentContainer.ResumeLayout();
                }
                catch (Exception ex)
                {
                    as_msg = "创建控件失败,原因为:\n" + ex.Message.ToString();
                    return -1;
                }
                return 0;
            }