2016-08-01 70 views
0

我想創建一個用戶控件使用Windows窗體PanelLabel s的一些文本動態添加到Panel水平。我想用下面的代碼和Label s被覆蓋。用戶控件使用面板和標籤水平動態添加

public partial class AllergyBar : Panel 
{ 
    public AllergyBar() 
     : base() 
    { 
     InitializeComponent(); 
    } 

    int X = 0, Y=0; 

    int height, width; 
    public AllergyBar(List<String> lstAlerts) 
     : base() 
    { 

     this.BackColor = System.Drawing.Color.WhiteSmoke; 
     this.Name = "panel2"; 
     this.Size = new System.Drawing.Size(75, 23); 
     this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; 
     foreach (string alert in lstAlerts) 
     { 
      Label AllergyLabel = new Label(); 
      AllergyLabel.Text = alert; 
      width = AllergyLabel.Size.Width; 
      Y = AllergyLabel.Location.Y; 
      AllergyLabel.Location = new System.Drawing.Point(X+width, Y); 
      AllergyLabel.Size = new System.Drawing.Size(75, 23); 
      AllergyLabel.AutoSize = true; 
      AllergyLabel.BorderStyle = BorderStyle.FixedSingle; 
      AllergyLabel.Dock = DockStyle.Fill; 
      this.Controls.Add(AllergyLabel); 
     }  
     InitializeComponent(); 
    } 
} 
+1

使用FlowLayoutPanel的https://msdn.microsoft.com/en-us/library/system.windows.forms。 FlowLayoutPanel的(v = vs.110)的.aspx –

回答

0

你必須在每個循環的最後更新X值:

public partial class AllergyBar : Panel 
{ 
    public AllergyBar(): base() 
    { 
     InitializeComponent(); 
    } 

    int X = 0, Y=0; 

    int height, width; 
    public AllergyBar(List<String> lstAlerts): base() 
    { 
     InitializeComponent(); 
     this.BackColor = System.Drawing.Color.WhiteSmoke; 
     this.Name = "panel2"; 
     this.Size = new System.Drawing.Size(75, 23); 
     this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; 
     foreach (string alert in lstAlerts) 
     { 
      Label AllergyLabel = new Label(); 
      AllergyLabel.Text = alert; 
      AllergyLabel.Location = new System.Drawing.Point(X, Y); 
      AllergyLabel.AutoSize = true; 
      AllergyLabel.BorderStyle = BorderStyle.FixedSingle; 
      AllergyLabel.Dock = DockStyle.Fill; 
      X += AllergyLabel.Width; 
      this.Controls.Add(AllergyLabel); 
     } 
    } 
}