public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            panel1.AutoScroll = true;            panel1.ControlRemoved += new ControlEventHandler( panel1_ControlRemoved );
        }        void panel1_ControlRemoved( object sender , ControlEventArgs e )
        {
            System.Collections.IEnumerator enumerator = this.panel1.Controls.GetEnumerator();
            int index = 0;
            while ( enumerator.MoveNext() )
            {
                Control ctrl = (Control)enumerator.Current;
                if ( index == 0 )
                    ctrl.Location = new Point( 0 , 0 );
                else
                    ctrl.Location = new Point( 0 , ( index * ( 60 + 3 ) ) );
                index++;
            }
        }
        int height = 60;        private void button1_Click( object sender , EventArgs e )
        {
            Button btn = new Button();
            btn.Width = panel1.Width-4;
            btn.Height = height;
            btn.BackColor = SystemColors.ButtonFace;
            btn.Top = panel1.Controls.Count * height;
            btn.Text = Convert.ToString( panel1.Controls.Count + 1 );
            panel1.Controls.Add( btn );
            btn.Click += new EventHandler( btn_Click );
        }        void btn_Click( object sender , EventArgs e )
        {
            panel1.Controls.Remove( (Control)sender );
        }
    }
当点击button1添加多个button控件到panel中后,此时panel有滚动条,把滚动条拖到最低下,点击最后一个button移除后,再把滚动条往上拖到顶,就会发现空出来一大截,怎么让第一个控件到顶啊?

解决方案 »

  1.   

    在 panel1_ControlRemoved 方法内开始循环之前加上一句
    panel1.VerticalScroll.Value = 0;
    楼主你出现这样的问题应该是由于当前滚动条已经滚动到下方,这个时候设置location会从当前滚动条所处的最顶端位置开始算起。一些拙见。
      

  2.   

    调用下panel的AdjustFormScrollbars方法看看http://msdn.microsoft.com/en-us/library/system.windows.forms.scrollablecontrol.adjustformscrollbars.aspx
      

  3.   

    换了个实现方式,使用Dock属性。省了自己去维护位置的麻烦感谢两位的回复