C# WinForm panel 動態增加(自創)元件(UserControl)
C# WinForm panel 動態增加(自創)元件(UserControl)
Code:
private void rjButton1_Click(object sender, EventArgs e) { panel1.AutoScroll = true;//允許Scroll Bar panel1.Controls.Clear();//清空所有子元件 //--- //基礎定位點參數 int w = 10;//基本定位點 int h = 10; int column = 0;//列數 int row = 3;//行數 //---基礎定位點參數 ArrayList arrayList= new ArrayList();//元件陣列 for(int i=0;i<5;i++)//動態產生子元件並放到ArrayList { TakeawaysInfo TakeawaysInfoBuf=new TakeawaysInfo(); TakeawaysInfoBuf.Name = $"TakeawaysInfo{i}"; arrayList.Add(TakeawaysInfoBuf); } int Width = 0; int Height = 0; for (int i=0;i<arrayList.Count;i++) { if(( i!= 0) && ((i % row)==0)) { column++;//列數計算 } ((TakeawaysInfo)arrayList[i]).Location = new Point(w*((i%row)+1) +((i % row) * ((TakeawaysInfo)arrayList[i]).Size.Width), h*(column+1) +(column* ((TakeawaysInfo)arrayList[i]).Size.Height));//計算個元件的定位點 panel1.Controls.Add((TakeawaysInfo)arrayList[i]); Width = w * ((i % row) + 1) + ((i % row) * ((TakeawaysInfo)arrayList[i]).Size.Width) + ((TakeawaysInfo)arrayList[i]).Size.Width; Height = h * (column + 1) + (column * ((TakeawaysInfo)arrayList[i]).Size.Height) + ((TakeawaysInfo)arrayList[i]).Size.Height; } panel1.AutoScrollMinSize = new System.Drawing.Size(Width, Height);//觸發長出Scroll Bar }