当将控件拖放到设计器中的form时,会自动生成代码,可是我需要添加大量的按钮控件,总不能一个个的拖拽吧,我想声明一个按钮数组,然后用循环实例化并添加到容器中,可是代码视图中是不允许编辑的,我该怎么在form的构造函数中添加这块代码啊?对于C#我是初学者,还不熟悉VS的使用,以前用java做的。
    还有,用C#做windows应用程序必须要新建windows窗体应用程序项目吗,能不能完全是自己写代码啊?感觉这样自己能对逻辑有更好的把握。

解决方案 »

  1.   

    就是在构造函数中
    public Form1()
    {
        InitializeComponent();    // 添加100个按钮
        for (int i = 0; i < 100; i++)
        {
            Button btn = new Button();
            // 设置按钮文字,大小位置,注册事件 等
            this.Controls.Add(btn);
        }
    }
      

  2.   

      1:          for (int i = 0; i < 4; i++)
                {
                    Button a = new Button();
                    Controls.Add(a);
                    a.Location = new Point(100*i, 200*i);
                }   2:如果你要构建有窗体的程序,那你就只能选择VS自带的应用程序类型,不能像你说的那样的.
      

  3.   

    纯手写的话你必须很了解.NET下面winform的一些机制 但是最主要的是你选择了什么项目类型就会按那个项目去编译 纯手写的话你可能会选择类库项目类型 但是用VS编译出来的话那就成了个DLL 除非你手动在CMD下面编译
      

  4.   

    如果你想对逻辑有更高的控制 完全可以自己重写form类的相关方法 或者其他控件的相关方法 不然我们需要继承这种东西干什么~
      

  5.   

    看一下Form1的后台代码,就知道你拖控件时编辑器干了嘛?
      

  6.   

    我不是这个意思,我是说怎么在VS自动生成的代码中添加自己写的代码,比如在InitializeComponent()函数中写自己的初始化代码
      

  7.   

            /// <summary>
            /// 设计器支持所需的方法 - 不要
            /// 使用代码编辑器修改此方法的内容。
            /// </summary>
            private void InitializeComponent()
            {
                this.button1 = new System.Windows.Forms.Button();
                this.SuspendLayout();
                // 
                // button1
                // 
                this.button1.Location = new System.Drawing.Point(66, 101);
                this.button1.Name = "button1";
                this.button1.Size = new System.Drawing.Size(75, 23);
                this.button1.TabIndex = 0;
                this.button1.Text = "button1";
                this.button1.UseVisualStyleBackColor = true;
                this.button1.Click += new System.EventHandler(this.button1_Click);
                // 
                // Form1
                // 
                this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.ClientSize = new System.Drawing.Size(284, 262);
                this.Controls.Add(this.button1);
                this.Name = "Form1";
                this.Text = "Form1";
                this.ResumeLayout(false);
     
                button1.Location = new System.Drawing.Point(200, 200);        }